You'll get your Mac news here from now on...

Help TMO Grow

The Mac Observer Express Daily Newsletter

Home
News
Tips
Columns & Editorials
Reviews
Reports
Archives
Search
Forums
Software
Reports
Contact

by Stephen Swift

AppleScript: Variables and Other Stories
April 2nd, 2002

[Author's Note: This marks the 5th installment of AppleScript: The Macintosh Autopilot. If you find any of this tutorial not making sense, check out the some of the earlier installments.]

Think back to your youthful days of high school and the ten daily math problems from your algebra teacher. Remember the look you gave your teacher when he or she put on the board 4 + x = 7; solve for x? That day you learned about variables. Today, you'll learn about variables in AppleScript.

AppleScript could solve that equation for you. Type in set x to 4 + 3, run the script, and 7 should appear in the result window. Now you have a sophisticated calculator - whoopee! Sarcasm aside, variables become very useful in AppleScript. They help you use objects of which you don't know the name, or when the name might change.

## How They Work

Syntax:
set someVariable to someValue
or
copy someValue to someVariable

You always have to set the variable to the value, not the other way around. You'll get an error if you try to set 7 to x. You always have to copy the value to the variable. Why do I have two methods of defining variables? See Copy Vs. Set later on in this article. A variable is a replacement for an object or action. Let's say we needed to add 4 + 3 many times in a script. We could just write out 4 + 3 every time, or we could write it out once and set it to x. Then, every time we needed to add 4 and 3, we would just type x. AppleScript isn't adding 4 + 3 every time we type x. When we set 4 + 3 to x, AppleScript adds 4 and 3 and gets 7 as the result. When you call up the variable, you are just calling up the value that AppleScript has assigned to it.

## A Variable By Any Other Name…

The basic rules for variable names:
1. Variables are not case sensitive. If you set Variable to 7 variable will also equal 7.
2. The only characters you are able to use are 0-9, a-z, and _ (the "underscore" character).
3. You can't start a variable with a number.
4. You can't make a known term in AppleScript into a variable. For example, tell can't be a variable because it already means something else.
5. If you want to defy rules 2-4, enclose your variable in ||. So |\$ 9.x| and |tell| would be variables.

The way you write variables is totally up to you. Here are some tips for writing good variables.

1. You want your variables long enough so that you understand what they represent, but short enough so that it doesn't take too long to write it.
2. Separate words with capital letters or _ characters. MyVariable or my_variable is easier to read than myvariable.
3. Avoid enclosing your variables in || when you can.
Copy vs. Set

When you set a variable to a value, AppleScript just replaces the variable with the value.

set List1 to {1, 2, 3}
set List2 to List1

In this example, AppleScript sees List2 and knows to look at List1 for the value. AppleScript sees List1 and sees {1,2,3} as the value. It then relays the information back to List2.

set item 1 of List1 to 4
get List2

After we add these lines on, AppleScript goes to List1 for the value to List2. The value for List1 has been changed to {4,2,3}. Because List2 looks to List1 for the value, if you change List1, you are changing List2.

set List1 to {1, 2, 3}
copy List1 to List2

Now, you are making a copy of List1 and calling it List2. When you call up List2 in AppleScript, it will have its own value, and won't rely on List1 for the information.

set item 1 of List1 to 4
get List2

If you change the value of List1, List2 will stay the same original value.

In general, use set. You rarely need to use copy, unless you want to make a new variable from pre-existing data.

A Real World Application

I've set up an AppleScript to monitor the space available in my hard disk. I need to use variables, because the space available will be constantly changing not to mention my hard drive name.

tell application "Finder"
set diskName to (name of startup disk)
set diskSpace to (free space of startup disk) (*Number of bytes free.*)
set diskSpaceto (round (diskSpace / 1048576)) (*Changes bytes into megabytes.*)
set diskCap to (capacity of startup disk) (*Number of bytes that the disk can hold.*)
set diskCap to (round (diskCap / 1048576))
set Cushion to (round (0.2 * diskCap)) (*20% of the disk.*)
set diskSpace to (diskSpace - Cushion) (*Amount of space left in disk.*)
set CurDate to ((current date) as string)

end tell

if diskSpace = 0 then

beep

end if

display dialog "On " & CurDate & " the drive, " & diskName & ", has " & diskSpace & " MBs available." buttons {"OK"} default button "OK" with icon note

Save this script in the startup items folder to have it monitor your hard drive each time you start up your computer. You should be careful of a few things. In math, 3*4+7=19 but 3(4+7)=33 because order of operations tells us to perform the task in the parentheses first. This is the same in AppleScript. For example, in our second line we can't set diskName to name. Since that doesn't make sense in English, it's not going to make sense to AppleScript. You have to enclose the item you want to set diskName to in parentheses. AppleScript will perform that task, then set the result to the variable. I also use a simple if statement to find out if I'm eating into my cushion. If the amount of disk space left is less than or equal to 0 then the computer will beep at me. If you want, you could also have AppleScript load Macmall.com so you can search for a new hard drive. In addition, you should recognize the display dialog command from the previous article. Go back to review instructions for creating a dialog box if you need to.

AppleScript Formatting

Now it's time for you to be introduced to the different parts of code in AppleScript. Here's the formal introduction we've all been waiting for. The styles of each part are relevant only if you have set them up the same way I have (See Figure 1).

Uncompiled (New Text) - New text is uncompiled code meaning that AppleScript hasn't checked it for errors yet.
Operators - These make up the structure for your script. Think of them as punctuation.
Values - This is the data that you feed your script. They consist of numbers, strings (text), and lists.
Variables - This adds flexibility to your script. When the data changes, you can still call it up.
Language Keywords - Commands understood by certain applications. They could act like nouns or verbs depending on the word.
Application Keywords - - Commands and words understood by AppleScript. These act as verbs, conjunctions, or prepositions.
Comments - Text ignored by AppleScript. This is just information for your own benefit.
References - You will never find a reference in a script. They are results from actions in the script found in the Event Log.

### What We Covered

• What variables are and how they are used in AppleScript.
• Created a script that would monitor free space on our hard drive.
• Reviewed the parts of AppleScript code.

### Next Time

• Recording data and creating new files will be covered.
• I'll also take a look at some items that can cause pitfalls in AppleScript.

### Extra Help

If you would like some help with a project or problem with AppleScript, I'd be glad to answer any of your questions. I'd also like to hear what people are doing with AppleScript. You can write me at Stephen@macobserver.com.

Comments or Questions? Is this column going to slow or fast for you? Do you want to script something, but don't know how? Do you need something explained or have a question about a script?  My E-mail address, stephen@macobserver.com, is open 24 hours a day, 7 days a week.

Most Recent AppleScript Columns

Repeat Yourself With AppleScript
June 12th

AppleScript Lists
June 5th

AppleScript

Back to The Mac Observer For More Mac News!

 [Podcast]

 We also offer Today's News On One Page! Yesterday's News

We also offer Yesterday's News On One Page!

Mac Products Guide
 New ArrivalsNew and updated products added to the Guide. Hot DealsGreat prices on hot selling Mac products from your favorite Macintosh resellers. Special OffersPromotions and offers direct from Macintosh developers and magazines. SoftwareBrowse the software section for over 17,000 Macintosh applications and software titles. HardwareOver 4,000 peripherals and accessories such as cameras, printers, scanners, keyboards, mice and more.

 © All information presented on this site is copyrighted by The Mac Observer except where otherwise noted. No portion of this site may be copied without express written consent. Other sites are invited to link to any aspect of this site provided that all content is presented in its original form and is not placed within another .