Subroutines

Subroutines are code units that can be used over and over again throughout the script once they are defined in the AppleScript program. They are essentially user-defined commands. Subroutines or handlers in AppleScript can be called with or without parameters, similar to functions in other languages. The subroutine can return a value to the calling script or simply perform a task and exit without returning a value. You can do almost whatever you want in a subroutine (except define another subroutine within it), including declare and initialize variables and call other functions. Example 1-15 creates a simpler way of producing a character from its ASCII decimal number equivalent. It calls the ASCII character scripting addition to produce the value.

Example 1-15. Simple AppleScript User-Defined Subroutine
set let to chr(67)-- the variable is set to 'C'
on chr(int)
   return ASCII character int
end chr

To define a subroutine in AppleScript, use the keyword on followed by the subroutine name, an opening parenthesis character, one or more optional variables that represents any subroutine arguments, and a closing parenthesis. If you have more than one parameter, then separate them with commas. Subroutines that do not have any parameters require empty parentheses, as in on chr( ). The end chr part, or simply end, is also required (Script Editor will automatically add the name of the subroutine after end if you forget to do it yourself). Whatever you want the subroutine to do is ...

Get AppleScript in a Nutshell 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.