8.8. Local/Global Variables and Variable Scope

In this section, I show you the difference between local and global variables. It's important that you fully understand the nature of a variable's scope. The scope is the extent to which a variable is known within a program. For example, you already know that the scope of a local variable is the handler within which it is defined. That is, the variable cannot be accessed from outside the handler.

A local variable can be explicitly declared as such by placing the keyword local in front of the variable name, like so:

local sortList

Note that variable declared to be local in this manner does not have a value assigned to it. You still have to do that before you use it in an expression.

If you intend to use a variable only within a handler, it is good programming practice to declare it local in this fashion. Why? Because if you do this, you avoid the possibility of overwriting the value of a global variable that might be defined outside the handler with the same name. You learn more about global variables later in this section. As you might surmise, the scope of a global variable is, well, global. That is, its value can be accessed from anywhere within the source file. You can declare more than one variable to be local on the same line by separating each variable with a comma.

Suppose you have a variable named x in your program and you want to access its value from inside a script. The following test handler shows the simplest way to do ...

Get Beginning AppleScript® 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.