Code and the Run Handler

So far, we've talked about blocks, and in particular about script object and handler definitions, as the constituents of a script. But of course there's more to a script than that: there's the actual code, the commands, the stuff that does something. From a visual point of view, code can appear anywhere. But wherever code appears, if you work your way up the levels of nesting, sooner or later you'll always come to either a handler or a script object. That's what the code is really inside of.

For example:

set x to 1
on outer( )
    set xx to 1
    script s
        set xxx to 1
        on sayHowdy( )
            display dialog "howdy"
        end sayHowdy
        set xxxx to 1
    end script
    set xxxxx to 1
end outer
set xxxxxx to 1

That script is exactly the same as an earlier example, except that I've added code lines, so that given the structure of the script (a handler in a script object in a handler), at least one line of code appears in every place where code can possibly appear. All the lines of code are set commands, except for the display dialog command in the middle. So now consider the line "set xx to 1." Where is it, structurally? It's inside the handler outer. You can do this for every line of code.

This little game is significant because the regions demarcated by the handler and script object definitions are also regions of scope. The line "set xx to 1" talks about a variable called xx. Because of how and where this line occurs, there are strict rules about what parts of the script can and can't see this ...

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.