Language Guide
CHAPTER 8
Handlers
226 Using Subroutines
To generate 10 factorial, the subroutine factorial is called once from the
top level of the script, and then calls itself ten more times, until the value of
x is 0. When x is equal to 0, AppleScript skips to the Else clause and finishes
executing all the partially executed subroutines, including the original
factorial subroutine call.
When you call a recursive subroutine, AppleScript keeps track of the variables
and pending statements in the original (partially executed) subroutine until the
recursive subroutine has completed. The limit on the number of pending
subroutines depends on the amount of memory available.
Saving and Loading Libraries of Subroutines 8
So far, you’ve seen examples of defining and calling subroutines in the
same script. This is useful for functions that are repeated more than once in
the same script. But you can also write subroutines for generic functions, such
as numeric operations, that are useful in many different scripts. To make a
subroutine available in any script, save it as a compiled script, and then use
the scripting addition command Load Script to make it available in a particular
script. You can use this technique to create libraries of subroutines for use
in many scripts.
For example, the following script contains three subroutines:
centimeterConversion, which converts inches to centimeters;
factorial, which returns the factorial of a number; and min, which
returns the smallest number in a list of numbers.
--the centimeterConversion subroutine converts inches to centimeters
on centimeterConversion from x
if class of x is contained by {integer, real} then
return x * 2.54
else
error "The parameter must be a real number or an integer."
end if
end centimeterConversion