Syntax of Defining and Calling a Handler
The way a handler is defined (in the on
line) states how many parameters the handler takes (and also supplies names for variables in the handler to which the parameter values will be assigned during a call). A call to the handler must correspond, supplying parameters correctly. It is a runtime error to call a handler with fewer parameters than the definition of the handler requires:
on greet(what)
display dialog what
end greet
greet( ) -- error: {} doesn't match the parameters
{what} for greet
The nitty-gritty of how a handler's definition states how many parameters there are, and how a corresponding call to that handler must be phrased, is remarkably complicated. There are actually four cases that must be distinguished (though you are most likely to use only the first two in handlers that you define). I'll discuss these four cases in a moment, but first I want to talk about the problem of optional parameters.
Optional Parameters
Officially, there is no way to declare a parameter optional in AppleScript. On the other hand, you really don't need a way to do this, because a parameter can be a list or a record, which can have any number of items. (Gosh, all we need is a shift
command and this would be Perl!)
For example, here's a handler that calculates the area of a rectangle given the lengths of the two sides. If you pass the length of only one side, the rectangle is assumed to be a square:
on area(L) set a to item 1 of L if (count L) = 2 then set ...
Get AppleScript: The Definitive Guide, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.