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
Definition
The code in that last example, as a complete script, will compile,
but it won’t run; at runtime, it generates an error.
That’s because
x
has never been assigned a value. 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. An AppleScript
variable is not defined until you first give it a value explicitly.
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 shoebox, labels it “x”, and puts 5 into it. Now the second line runs fine, because there is a shoebox “x” from which to fetch a value.
Once a variable has been defined in the course of ...
Get AppleScript: The Definitive Guide 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.