Variable Scope

Variable scope refers to the loc ation in a script where variable values can be accessed. A variable that can be accessed anywhere in the script is known as global and has to be declared as such in the script:

global aVariable

AppleScript variables are local by default, meaning that if a script contains both script statements and function or subroutine definitions, then the variables that are declared inside of the function(s) are local (i.e., trying to access them outside of a function raises an error) unless declared as global outside the routine. This element is best illustrated by an example:

set aNum to 7
display dialog (do_it(aNum) as string) (* call the do_it function and display 
its result *)
log avar (* avar variable is not visible at this location; this causes an error
*)
 (* subroutine definition *)
on do_it(v)
   set avar to 0 -- avar is local to the subroutine
   set avar to v + 1
   return avar
end do_it

This script sets an integer variable to 7, then displays the results of a function call using the display dialog scripting addition. The do_it function is defined inside the script. It has an avar variable that is initialized to then used to add 1 to the integer argument that is passed to the function. Though the avar variable provides the return value for the do_it function, it is only known inside the function. The third line of this example, which tries to log the avar value in the Script-Editor Event Log window, raises an error because the avar variable’s ...

Get AppleScript in a Nutshell 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.