DekGenius.com
Team LiB   Previous Section   Next Section

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.

Example 8-1. Simple Subroutine Definition
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 the subroutine definition:

myfunc("one string ", "connected to another")

AppleScript also supports an unwieldy (my humble opinion, of course) form of subroutine that includes labeled parameters (see Section 8.2). This chapter concludes with a discussion of the five special built-in Apple-event handler types listed in Table 8-1.

Table 8-1. Five Built-in AppleScript Handlers

idle handler

open handler

reopen handler

quit handler

run handler

    Team LiB   Previous Section   Next Section