Access to variables
-
To define a new variable, or to assign a value to an existing variable, you use set ... to, followed with a valid expression.
Run the following script.
set x to 1 + 1
The result prints to the console: 2.
-
An expression may include other variables and calls to functions.
Run the following script. Note that if the x variable does not exist, the script will make an error: make sure that you have run the previous example.
set x to x + 1
-
To get the contents a given variable, use get.
Run the following script.
get x
The result (the value of x) prints to the console.
Alternately, you can get the contents of a variable by evaluating the expression made of that variable alone. Select any x in any AppleScript terminal, then validate: the contents of the x variable will print to the console.
The classes of variables
The most usual data types are the following.
- boolean: stands for true or false.
set x to (1 = 1.0)
- integer: an integer number.
set x to 1
- real: a real number.
set x to 1.1
- string: text. You define a string by encapsulating any sequence of characters between double-quotes (escape double-quotes and backslashes with backslash \).
set x to "abc"
- list: a list of any quantities. You define a list between brackets, separating items with commas.
set x to {1, 1.1, "abc"}
To access an element in a list, use the item keyword.
get item 2 of x
- record: a list of key-value pairs, where the key is a string conformant to the rules for a variable's name, and where the value is any quantity.
set x to {i:1, radius:1.1, s_2:"abc"}
Access is by key only (item does not work in records).
radius of x
- array of real: an array of real numbers (stored as a packed binary array of double-precision real numbers).
set x to createarray 10
- matrix: a 2D array of real numbers.
set x to ArrayToMatrix((createarray 10), 2, 5)
-
References to objects of Smile.
set x to window 1
AppleScript is a versatile language, particularly regarding variables' classes. Most often, you do not explicitly declare the class of a variable, for instance set x to 1 + 1 will implicitly return an integer while set x to 1.0 + 1 will make a real number.
The class property is how you get the class of a variable: class of x.
In many cases you can use the as preposition to force a variable to a different class. This is called coercing, or typecasting.
set x to "1.234" as real
-- 1.234
Displaying variables
The display command is how you produce a text version of the contents of any variable. Various commands display text, making it natural to display information about the run while a script is executing.
- quietmsg(s): displays the string s in the console,
- msg(s): like quietmsg(s), but brings the console to the front,
- postit s displays a message in the floating Message window. postit "" closes the floating Message window.
postit "job in progress …"
set x to 1
quietmsg(x)
set x to x + 1
quietmsg(x)
set x to x + 1
quietmsg(x)
postit "job done"
Import script
|