Language Guide

CHAPTER 8
Handlers
Using Subroutines 225
Checking the Classes of Subroutine Parameters 8
You cannot specify the class of a parameter in a subroutine definition. You can,
however, get the value of the Class property of a parameter and check it to
see if the parameter belongs to the correct class. If it doesn’t, you may be able
to coerce it with the As operator, or failing that, you can return an error.
(For information about coercing values, see Chapter 6, “Expressions.” For
information about returning errors, see “Try Statements,” which begins on
page 204.)
Here’s an example of a subroutine that checks to see if its parameter is a real
number or an integer:
on CentimeterConversion from x
--make sure the parameter is a real number or an integer
if class of x is contained by {integer, real}
return x * 2.54
else
error "The parameter must be a real number or an integer"
end if
end CentimeterConversion
Recursive Subroutines 8
A recursive subroutine is a subroutine that calls itself. Recursive subroutines
are legal in AppleScript. You can use them to perform repetitive actions. For
example, this recursive subroutine generates a factorial.
on factorial(x)
if x > 0 then
return x * (factorial(x - 1))
else
return 1
end if
end factorial
factorial(10)