Variable Names

The name of a variable must begin with a letter or underscore and must consist entirely of alphanumeric characters or underscore. So a variable name must begin with a character in the character set [a-zA-Z_] and must consist entirely of characters in the character set [a-zA-Z0-9_].

Variable names are case-insensitive at compile time . That means the following code will compile and run:

set myVar to 5
set myvar to myvar + 1

AppleScript assumes that myvar in the second line is the same variable as myVar in the first line. Furthermore, as a reflection of this assumption, AppleScript rewrites the variable names after compilation so that their case matches the first usage of the name:

set myVar to 5
set myVar to myVar + 1

This suggests a trick that can help you spot undeclared variables: in your declarations, use an uppercase letter somewhere in every variable name; elsewhere, never use an uppercase letter in a variable name. Then, after compilation, any variable name without an uppercase letter must be an undeclared variable. For example, here’s some code that I typed following these rules, after compilation:

local myVar
set myVar to 5
set mybar to myVar + 1

In that code I have accidentally created and set the value of an unwanted variable mybar in the last line. I meant to say myvar, but I mistyped it. This won’t cause AppleScript to generate any error, and the script will misbehave. The chances that I will spot my mistake are increased by my use of the case trick.

Once ...

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.