Chapter 8. Subroutines
A subroutine is a piece of code or sequence of statements that is defined in a program or script and can be used repeatedly throughout that script. AppleScripters traditionally refer to this programming construct as a “handler.” When the script calls the subroutine, the flow of code execution branches to the statements in the subroutine. Those statements are executed and may or may not return a value to the segment of the script that called the subroutine. Then the script execution resumes at the statement following the subroutine call.
AppleScript
subroutines are not that much different than they are in other
programming languages. AppleScript supports the creation of
subroutines with positional parameters. This
means that the subroutine definition begins with the keywords
on
or to
and a subroutine name
that does not clash with any of AppleScript’s other
predefined names (such as anything
or
pi
), and then a set of parentheses that optionally
lists any parameters or values that should be passed to the
subroutine. The subroutine in Example 8-1 is called
myfunc.
on myfunc(s1,s2) return (s1 & s2) end myfunc"
This example concatenates or combines two strings that are passed to the subroutine as parameters (for the sake of brevity I have left out the typical checks that you would include for whether the parameters are valid strings). When calling myfunc in code, the parameters have to be in the same order as they are in ...
Get AppleScript in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.