Scope of Globals

An explicit global is a variable whose name appears in a global declaration . A global declaration can declare several variables at once, delimited by comma:

global a
global b, c, d

Globals are rather complicated. I'll divide the discussion into two parts: the downward effect of a global declaration, and its upward effect.

Global Declarations: The Downward Effect

The downward effect of a global declaration is very much like a top-level entity declaration. A variable declared global is visible in the scope where it is defined, subsequent to the point where it is defined, and at all deeper levels within that scope, subsequent to the point where it is defined.

For example:

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

The variable x is declared global; it is then visible downward into the scope of myHandler, because myHandler is defined subsequently in the same scope as x.

But the following code does not work:

set x to 5
on myHandler( )
    display dialog x
end myHandler
global x
set x to 10
myHandler( ) -- error: The variable x is not defined

We keep setting x like mad, but to no avail; the global declaration doesn't come until after the handler definition, so code inside the handler can't see x.

Just as with a top-level entity, a global's downward effect is overshadowed by a local declaration of the same variable name at a deeper level, and this overshadowing affects only the scope of the local declaration—not a deeper scope.

Global Declarations: ...

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.