3

I understand that it is possible to trigger an .scpt file that is saved somewhere on my computer from within a different .scpt file.

Can I call a specific subroutine of that .scpt file from a different .scpt file? I want to skip over the entire script, and only run the code that is found in one, specific subroutine

I understand that I can simply copy the subroutine into its own, dedicated .scpt file and accomplish what I want that way. This method is demonstrated in this answer. However, I would prefer not to have to do this, for the sake of convenience.


In addition, is it possible to also pass variables to that subroutine? My current need does not require this ability, but I am still curious.


1

AppleScript's load script

AppleScript's load script command will do what you want.

Example

On your Desktop, save a .scpt file containing the following saySomething handler:

on saySomething()
    say "hello"
end saySomething

Then within another script you can call saySomething:

set myOtherScript to load script (alias ((path to desktop folder as string) & "external.scpt"))
myOtherScript's saySomething()

The returned object from load script is a script object. Once loaded, the script object is treated as local and can have its local handles called, including with parameters.

See Can I put shared applescript code in a separate file and load it in various scripts? for more examples.

| improve this answer | |
0

You have three questions in your OP...

  • The Title: How to call a specific subroutine of an AppleScript from another AppleScript?

    This is actually answered by the link, within the linked answer, in your OP and also touched on by Graham Miln's answer.

  • Can I call a specific subroutine of that .scpt file from a different .scpt file? I want to skip over the entire script, and only run the code that is found in one, specific subroutine.

    This is the good question because the documentation and examples focus on the handlers themselves and tend to show that external scripts being called should just be a collection of handlers and no other AppleScript code.

    Well, as an old saying goes... proof is in the pudding... The answer is yes, you can call a handler from another filename.scpt file that contains any valid AppleScript code. Note that the target of the load script command will load the entire script to memory however, will not execute anything other then the handler(s) called.

  • In addition, is it possible to also pass variables to that subroutine?

    Providing the handler being called is written to take parameters, then yes you can pass it a variable that has already been assigned and pass it as a parameter.

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .