Closures

A closure is one of those delightfully LISPy things that turns up in AppleScript. The subject is rather advanced, though, so don't feel you have to understand everything in this section at once.

It turns out that a script object may capture certain aspects of its context, maintaining this context even though the script object may run later in a different context. For example:

property x : 5
script myScript
    display dialog x
end script
set x to 20
set dummy to myScript
set x to 10
run myScript -- 20

That is extremely odd. It violates the rule stated earlier ("Free Variables") about the value of free variables being determined at runtime. By the time myScript runs, its free variable x has been set to 10, yet the dialog displays 20. The proximate cause turns out to be the mysterious line "set dummy to myScript." If that line is removed, the dialog says 10, just as we expect. Yet it is hard to see what difference that one line can make. It's not as if we ever do anything with the variable dummy, after all. We simply assign to it and forget about it. So what's going on?

The rule appears to be that the mere act of assigning a script object variable to another variable—it can equally be a copy as a set—causes the script object to become a closure . A closure is a scope block plus the values of its free variables at that moment.

The example is structured in three parts so as to demonstrate the phenomenon fully. First, a property declaration precedes the script definition; this is how ...

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.