Using Subroutines
Subroutines are collections of statements that AppleScript runs in response
to user-defined commands. They are similar to functions, methods, and procedures in other programming languages. This section explains how to write and call subroutines.Subroutines are useful in scripts that perform the same action in more than one place. For example, if you have a series of statements for comparing values and you need to use those statements at several places in a script, you can package the statements as a subroutine and call it from anywhere in the script. Your script becomes shorter and easier to maintain. In addition, you can give subroutines descriptive names that make their purposes clear and make scripts easy to read.
Here's a subroutine, called
minimumValue
, that returns the smaller of
two values:
--minimumValue subroutine: on minimumValue(x, y) if x � y then return x else return y end if end minimumValue --how to call minimumValue: minimumValue(5, 105)The first line of theminimumValue
subroutine specifies the parameters of the subroutine. These can be positional parameters--likex
andy
in the example--where the order of the parameters is significant, or labeled parameters-like those for AppleScript and application commands--where the order of parameters other than the direct parameter doesn't matter.The
minimumValue
subroutine includes two Return statements. A Return statement is one of the ways a subroutine can return a result. When AppleScript executes a Return statement, it returns the value (if any) listed
in the statement and immediately exits the subroutine. If AppleScript executes a Return statement without a value, it exits the subroutine immediately
and does not return a value.If a subroutine does not include any Return statement, AppleScript executes the statements in the subroutine and, after handling the last statement, returns the value of the last statement in the subroutine. If the last statement does not return a value, then the subroutine does not return a value.
When AppleScript has finished executing a subroutine, it passes control to the place in the script immediately after the place where the subroutine was called. If a subroutine call is part of an expression, AppleScript uses the value returned by the subroutine to evaluate the expression. For example, to evaluate the following expression, AppleScript calls the subroutine for
minimumValue
.
minimumValue(5, 105) + 100After the value ofminimumValue
is returned, AppleScript evaluates the rest of the expression.
Subtopics
- Types of Subroutines
- Scope of Subroutine Calls in Tell Statements
- Checking the Classes of Subroutine Parameters
- Recursive Subroutines
- Saving and Loading Libraries of Subroutines