Scope of Undeclared Variables

In AppleScript, you do not have to declare variables. When you use a name that, by the preceding rules of scope, is not an existing variable, AppleScript does not complain; rather, it creates the variable for you. How it does this depends upon the location of the code that uses the nonexistent variable name:

Code at the top level

The variable is created as a global. There is no explicit global declaration, so there is no downward effect, but other scopes can see this variable through a global declaration. I call this an implicit global.

Code not at the top level

The variable is created as a local. I call this an implicit local .

Let's illustrate an implicit global first:

set x to 5
on getX( )
    global x
    display dialog x
end getX
getX( ) -- 5

The first line never said explicitly that x should be a global. But it clearly is one, since when getX comes along and asks to see a global called x, the x created in the first line is what it sees. (Incidentally, you can move the "set x to 5" line to after the getX handler definition and the script will still work; the important thing is that the global x be defined by the time getX runs, not necessarily before getX itself is defined.)

Incidentally, a variable created implicitly in a script's top-level explicit run handler is an implicit global as well, just as if you'd declared it at the absolute top level:

on run
    set howdy to "Howdy"
    sayHowdy( ) -- Howdy end run on sayHowdy( ) global howdy display dialog howdy end ...

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.