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( ) -- 5The 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 ...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.
Read now
Unlock full access