MacOS – How to call a specific subroutine of an AppleScript from another AppleScript

applescriptmacos

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.


Best Answer

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.