Declaration and Definition of Variables

There is no requirement in AppleScript that variables be declared explicitly. The rule is basically that if you use a word that AppleScript doesn't understand, the word is assumed to be the name of a variable. The following code, as a complete script, will compile just fine:

set x to x + 1

Although it is not necessary to declare a variable, it is possible to declare a variable. I'll explain how you do this, and argue that there are good reasons for doing it, in Chapter 10.

Definition

The code in that last example, as a complete script, will compile, but it won't run; at runtime, it generates an error. The error message reads: "The variable x is not defined." The problem is not that the variable x has never been declared! There is no need to declare it. AppleScript understands (or assumes) that x is supposed to be a variable. Nor is the problem that you are trying to assign to it. The problem is that you are trying to fetch its value, and it has no value. That's because x has never been assigned a value. An AppleScript variable is not defined until you first explicitly give it a value. To continue our shoebox analogy, there is no "x" shoebox to fetch the contents of, because you've never put anything into it.

This code both compiles and runs:

set x to 5
set x to x + 1

During execution of the first line, AppleScript observes that you're putting something into the "x" shoebox, but there is no such shoebox as yet. No problem; AppleScript creates the ...

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.