What is a Variable?

set my_message to “hello world”
say my_message

What is a Variable?

In the above code, my_message is the name of the variable. “hello world” is the information the variable holds. After you define the variable, every time you use the variable in the code, the script will replace the variable with the information that the variable holds.
When you run (play) the above code, the script translates line 2 to be:  say “hello world”

applescript_variable

A variable is kind of like a keyboard shortcut in some ways. It takes information you use over and over and gives you a shortcut to access it. It is also how the program stores information received from applications and user input.

What can be a Variable?

•  You get to decide the name of the variable. It is best to use concise descriptions. There are some rules you need to play by. You can only use letters, numbers and underscores. Variables must begin with a letter.
•  Variables can not be words that applescript already uses. If you press compile and get an error, try adding a prefix to your variable. You might try my_file instead of file.
•  You can change the information a variable holds throughout the script. Just set the variable again.

You don’t have to overthink it too much. Applescript will tell you if what you are typing out doesn’t work. If you compile your script and your variable turns green – you’re good! If it doesn’t, adjust and try again.

Good to know: variables are case sensitive, and will automatically adjust all further uses of the variable to match the case originally used when defining the variable. This means that you can’t use the same variable with different cases as two different variables.

Why use Variables?

Variables can save time while writing your script. Defining a large piece of information with a one word variable saves time, but more importantly, if that information changes, you only need to change it once (where it is defined) instead of every instance in the script where that information is used. There are a few other reasons to use them and you will pick these up naturally as you progress your scripts.

Back to the Learning Guide

Add your comment

Your email address will not be published. Required fields are marked *