Scope of Locals

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

local a
local b, c, d

A local variable is visible only within the very same region of scope where it is declared—not outside it, and not at a deeper level. (But there's an exception, which we'll come to in a moment.)

Local variables completely disambiguate a name within their own scope, and local variables in other scopes can have the same name without conflict. Suppose a script object starts like this:

script myScript
    local x

The local declaration for x means that from now on when code in this script object's scope says x it means this local x and no other. What's more, other scopes may declare their own local x, they may declare a global x, they may bang the floor and have a temper tantrum, but they absolutely will not be able to have any effect upon myScript's x, nor will anything myScript does with its x have any effect upon them.

Here's an example of a local variable in action:

local x
set x to 5
script myScript
    display dialog x -- error: The variable x is not defined
end script
run myScript

Observe how completely different this is from what would have happened if x had been a top-level property. Here, there is a variable called x and it is defined, but it is declared local and therefore is visible only within its own scope. That scope is the top-level script. The display dialog x command is in a different scope, ...

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.