Skip to Content
AppleScript: The Definitive Guide, 2nd Edition
book

AppleScript: The Definitive Guide, 2nd Edition

by Matt Neuburg
January 2006
Beginner content levelBeginner
592 pages
16h 55m
English
O'Reilly Media, Inc.
Content preview from AppleScript: The Definitive Guide, 2nd Edition

Power Handler Tricks

A handler takes values as parameters and returns a value. A handler is a value. A script object is a value and can contain a handler. If these facts suggest to your mind an intimation of amazing possibilities, read on.

Handler and Script Object as Parameter

You can pass a handler as a parameter to handler. The difficulty is in calling it. This code fails with a runtime error:

on sayHowdy( )
    display dialog "Howdy"
end sayHowdy
on doThis(what)
    what( )
end doThis
doThis(sayHowdy) -- error: «script» doesn't understand the what message

The trouble is that AppleScript refuses to identify the what( ) in the handler call with the what that arrived as a parameter. This is actually another case of the rule (see "Handler Calls, Commands, and Script Objects" in Chapter 8) that an unqualified handler call is a message directed to the current script object, which in this case is the script as a whole.

One possible workaround is to use a global. This approach works because by copying the handler to a global we're putting it where a message directed to the script as a whole can find it (see "Scope of Globals" in Chapter 10):

on sayHowdy( )
    display dialog "Howdy"
end sayHowdy
on doThis(what)
    global what2
    set what2 to what
    what2( )
end doThis
doThis(sayHowdy) -- Howdy

This solution is clever, but now we've broken encapsulation. Global variables pose risks (other code might access this same global, or we might be tromping accidentally on some other code's global), and besides, if we're ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

AppleScript: The Definitive Guide

AppleScript: The Definitive Guide

Matt Neuburg
Mastering macOS Programming

Mastering macOS Programming

Gregory Casamento, Stuart Grimshaw

Publisher Resources

ISBN: 0596102119Errata Page