Scoping of Variables

The notion of scoping has to do with where an entity is visible. Your code consists of regions; these regions are each continuous, and some of them may be inside others, but they do not partially intersect—given two regions, either one is entirely inside the other or they are completely distinct. The region in which a variable is visible is called its scope. A variable that is visible at a certain point is said to be in scope at that point.

Scoping of variables in AppleScript is extraordinarily complicated (in my opinion). It’s also very important to understand, so don’t skip this section.

How Scoping Is Meaningful

Before we can talk about the scoping of variables in particular, you must understand the basic principles of AppleScript scoping in general. These are:

  • The top level of all scope is the script as a whole.

  • The regions of scope are handlers and script objects (and the top level).

  • A script object may contain a handler. A handler may contain a script object. A script object may contain a script object. But a handler may not (directly) contain a handler.

Let’s start with the first rule. Your script as a whole is itself the ultimate region of scope, containing everything else. So, let’s say that your script consists of just the following code:

set x to 7

In terms of scope, where are we when this code executes? This is all the code there is, and we’re not in a handler or a script object, so we are at the top level of all scope, the script as a whole.

Now I will ...

Get AppleScript: The Definitive Guide now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.