Language Guide

CHAPTER 8
Handlers
Scope of Script Variables and Properties 255
example accomplishes the same thing as the previous example, except that it
uses a global variable instead of a property to keep track of the count.
global theCount
increment()
on increment()
try
set theCount to theCount + 1
display dialog "Count is now " & theCount & "."
on error
set theCount to 1
display dialog "Count is now 1."
end try
end increment
When it encounters the identifier theCount at any level of this script,
AppleScript associates it with the theCount variable declared as a global at
the top level of the script. However, because a global variable declaration
doesn’t set the initial value of a property, the script must use a Try statement
to determine whether the value has been previously set. Thus, if you want
the value associated with an identifier to persist, it is often easier to declare
it as a property so that you can declare its initial value at the same time.
If you don’t want the value associated with an identifier to persist after a script
is run but you want to use the same identifier throughout a script, declare a
global variable and use the Set command to set its value each time the script is
run. Here’s an example:
global theCount
set theCount to 0
on increment()
set theCount to theCount + 1
end increment
increment() --result: 1
increment() --result: 2