Chapter 10. Scope

By scope is meant the ability of one region of code to see variables in another region of code. The rules of scope for AppleScript are remarkably involved—as involved of those of any computer language I know. They are a perennial source of pitfalls for beginning and experienced programmers alike. If you don't understand the rules of scope, or (even worse) if you try to ignore them, you'll find your scripts mysteriously going wrong in confusing ways. This chapter discusses the rules of scope, along with a powerful advanced scope-related feature of AppleScript—closures.

Regions of Scope

Every AppleScript program has regions of scope . Some regions of scope 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. In other words, the regions of scope are nested. The top level of the script is a script object and is a region of scope . Any other regions of scope are inside this, and are created by the presence of scope blocks: handler definitions and script object definitions. (See Chapter 6.)

In Example 10-1, I've sketched a sample script with scope blocks nested in various combinations. At every point where code can go, I've put a comment distinguishing that region of scope by number. So, scope 1 is the top level of the script itself (its implicit run handler); scope 2 is the code within handlerOne, a handler defined at the top level of the script; scope 3 is the code within ...

Get AppleScript: The Definitive Guide, 2nd Edition 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.