Previous Book Contents Book Index Next

Inside Macintosh: AppleScript Language Guide / Part 2 - AppleScript Language Reference
Chapter 8 - Handlers

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
      return y
   end if
end minimumValue
--how to call minimumValue:
minimumValue(5, 105)
The first line of the minimumValue subroutine specifies the parameters of the subroutine. These can be positional parameters--like x and y 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) + 100
After the value of minimumValue is returned, AppleScript evaluates the rest of the expression.

Types of Subroutines
Scope of Subroutine Calls in Tell Statements
Checking the Classes of Subroutine Parameters
Recursive Subroutines
Saving and Loading Libraries of Subroutines

Previous Book Contents Book Index Next

© Apple Computer, Inc.
13 JUL 1996