Language Guide

CHAPTER 8
Handlers
256 Scope of Script Variables and Properties
Each time the on increment handler is called within the script, the global
variable theCount increases by 1. However, when you run the entire script
again, theCount is reset to 1.
In the absence of a global variable declaration at the top level of a script, the
scope of a variable declaration using the Set command at the top level of a
script is normally restricted to the Run handler for the script. For example, this
script declares two separate theCount variables:
set theCount to 10
on increment()
set theCount to 5
end increment
increment() --result: 5
theCount --result: 10
The scope of the first theCount variable’s declaration, at the top level of the
script, is limited to the Run handler for the script. The scope of the second
theCount declaration, within the on increment handler, is limited to that
handler. AppleScript keeps track of each variable independently.
To associate a variable in a handler or a script object with the same variable
declared at the top level of a script with the Set command, you can use a global
declaration in the handler, as shown in the next example.
set theCount to 0
on increment()
global theCount
set theCount to theCount + 1
end increment
increment() --result: 1
theCount --result: 1
In this case, when AppleScript encounters the theCount variable within the
on increment handler, it looks for a previous mention of theCount not only
within the handler, but also at the top level of the script. However, references