AppleScript for Beginners II - Variables and Dictionaries

Before we dive into more on Script Editor and iTunes, let’s cover an important element in all scripts: the variable.

Remember those thrilling days in algebra where you learned to let x = 6 and to let y = 10? You then simply plugged in those values to perform problems like get x + 25, or get 80 / y? Is it all coming back to you? Very good; AppleScript is the same. A variable is nothing more than some sort of identifier for a value of some kind. The value can be a number, a list, a string, a file, a folder, a record, an action, or whatever else your script demands. The best part is that you can name the variables whatever you want (with some limitations) and the syntax used to tell AppleScript what to do with them is very simple; almost as simple as your algebra class:

set x to 6
set y to 10

See how easy that is? We use the term ‘set’ (instead of let) and the word ‘to’ instead of the equal sign. Now, let’s do some problems; add this line to the end of the last script:

get x + 25

When you run that script, see the number 31 in the Results pane? You are cooking! Now, add this line to the end:

get 80/y

You see that only the second result is displayed in the pane, even though you can bet that both calculations were performed. This is simply the way that the Results pane works; it always displays the result of the last action of the script. If you want to see both results at once, maybe we ought to try some new variables? And how about we make some creative names? Try substituting those last two lines with:

set xPlus25 to x + 25
set 80DividedByy to 80/y

You get an error, don’t you? The AppleScript rules for variable names are not difficult. You cannot use any AppleScript terms or keywords, nor can your variables start with a number. You cannot use a dash (-), but you can use an underscore (_). For our little example, try this in place of the last line:

set eighty_By_y to 80/y

The script now compiles, and it runs, but you still don’t get both values in the Results pane. No sweat. Since we now have variables that hold the results of both calculations, we simply put both variables on the last line of the script, but do NOT use any uppercase letters:

xplus25 & eighty_by_y

See how Script Editor automatically changes the case of the variables for you? This is extremely handy, and can actually help you debug your scripts. As long as you use the upper case letters the FIRST time you label a variable, Script Editor will do all the uppercase changes itself later on. When you then compile, you can quickly scan your script to make sure all your variables indeed possess the appropriate uppercase letters. If not, you probably have a typo somewhere and can easily fix it. Run the script now, and you will see both results of the calcuations in the Results pane.

Familiarity with variables is essential when working with any script, but especially when scripting applications. It is also a good idea to make your variable names something specific for the task at hand. DO NOT be afraid to use long variable names. There is nothing wrong with This_Is_A_List_Of_Every_Single_Song_I_Own as a variable name. The advantage is that when your scripts get longer and longer, you can keep track of your variables much more easily than if your variable name was simply TIALOESSIO.

To script applications, you also need to understand the concept of a Dictionary. When someone creates an application, they have the opportunity to create an AppleScript Dictionary so that the terms needed to script the application can be listed and sometimes explained. Script Editor provides two ways to peruse those dictionaries, and both have convenient keyboard shortcuts.

One way is to click on the File menu of Script Editor and choose Open Dictionary… (or the nifty keyboard shortcut of Shift-⌘-O). You are then presented with a list of all the applications on your machine for which Script Editor has located a scripting dictionary. You simply scroll through the list, click the application you desire, and the dictionary window magically appears.

A slightly more useful way is to access your Script Editor Library, by either choosing Library under the Window menu, or its keyboard shortcut of Shift-⌘-L. I like this one because it is more user-controlled. You can have as many or as few application dictionaries that you want in your library; you edit the list using the Plus and Minus buttons on the top of the Library window. (When you press the Plus button, you get a Finder-like window. Navigate to your Applications folder, and select the application whose dictionary you desire in your library. If it not scriptable, you will be told so.) If there is an application in the Library you feel you will NEVER want to script, highlight it in the Library pane, and click the Minus button. (The other two buttons will be covered shortly.)

What I really like about the Library is that when you quit Script Editor with the Library pane open, it opens again in the same place the next time you activate Script Editor. It really is like have the information right at your fingertips.

All right; with the Script Editor open, and the Library pane open, we are ready to look around in a dictionary and do some scripting! We are going to start with iTunes because it is free and pretty well accessible with AppleScript. Go to your library pane, highlight iTunes, and click the icon button that looks like a row of books.

(The response may not be immediate, especially if iTunes is not running. Whenever you open a scripting dictionary, the application associated with that dictionary also activates. Additionally, you will NOT be able to compile a script written for an application that is not on your machine, since part of the compilation is checking that application’s dictionary for term usage.)

You now have a window with three columns in the top half, and the bottom half extends all the way from one side to the other. The leftmost column (in the upper half of the window) has some peach squares with an ‘S’ in the middle next to the terms ‘Standard Suite,’ ‘iTunes Suite,’ and ‘Internet Suite.’ (Clearly, the ‘S’ stands for Suite.) These suites hold the dictionary information for their respective titles, specifically the AppleScript information as it relates to iTunes. The Standard Suite is nearly the same for all applications, that is, it describes the terms that are standard AppleScript for all applications. Any other suites listed are simply those that the application authors felt compelled to provide for scripters.

Now is probably a good time to note that not all AppleScript dictionaries are created equal. Many of them are almost unintelligible for the beginning scripter, since they are written by the software engineers who compiled the application in the first place. But do not be discouraged; even if you do not understand everything in the dictionary, it is still a great source of information for terms and commands to help you get your scripts functioning the way you desire.

Okay, now click on the iTunes Suite in the leftmost column of the upper half of the dictionary window, and watch the middle column. You see now a bunch of light blue circles with ‘C’ in the centers. These are Commands. A command is a word or phrase that requests an action; you want to make something to happen, so you script a command.

When you scroll down that middle column, you then come to a bunch of light purple squares, also with ‘C’ in the centers. These are Classes. A Class is a reserved word or phrase that specifies an object particular to that application. For instance, a track is a class within the iTunes application. This class has certain properties and elements that you can script. However, the term track is only recognized as a key word when used inside of a tell block for iTunes. (More tell block explanation is coming in 6 paragraphs; just hang in there for this part.) Check this script out (The script does not do anything, so no need to run it. Just compile it.):

tell application "iTunes"
	track
end tell
track

Do you see the different colors of both words, track? Inside of the tell block, it is a class; a reserved word that refers to a specific object of the iTunes application. Outside of the tell block, it means nothing all by itself; Script Editor assumes it is a variable name. Things get really exciting when you have two applications that both use the same keywords. As long as you keep your tell blocks straight, you have nothing to worry about. But that is an intermediate topic; on with the easy stuff.

One of the most useful classes in iTunes is the playlist, so scroll down the middle column of the upper dictionary pane, and highlight that term. (All the classes are in alphabetical order.) In the third column, you now see a peach square with an ‘E’ and more light purple squares with ‘P’ in the centers. These are elements and properties. An element is an object contained within another object. For example, a track object is an element of a playlist object, but it is possible to have a playlist with no tracks. In fact, if you go back to the middle column, you will see that track is also a class, just like a playlist.

A property, on the other hand, is a characteristic of an object that has a single value and is identified by a label. These are pretty interesting, and often the dictionary comes in very handy for them. Many properties are read-only (r/o), indicating that you certainly can use these properties in your scripts, but only as sources of information; you cannot change them.

Let’s go back to our playlist class in the middle column. When you highlight it, you will see the elements and properties listed to the right, and a bunch of definitions of the same items in the bottom pane. See the top property, duration? The listed definition tells you that it is read-only; you get the total length (in seconds) of all the tracks in that playlist. The name of the playlist, however, has no such (r/o) identifier, so you can expect that you can mess with that property.

OK, enough boring stuff; let’s write a little script. Here is one of the niftiest features of your Script Editor Library. Go back to the Library pane and look at the fourth little button to the right, along the top. See how it looks like a little piece of paper with a script icon? Make sure that iTunes is still highlighted on your Library list, and click that button.

Is that not cool? You are now presented with a new script window, complete with what is called a ‘tell block’ for the application you wish to script, and your cursor is right in the middle! Dang, I love that! Remember that whenever you want to tell an application to do something, you need a similar tell block. All tell blocks start with the line, tell application “So and so”, and end with the line, end tell. Everything in middle is what you are telling that application to perform. Some tell blocks contain dozens of lines to do dozens of things, but that is also a topic for the future. Right now, it is time to simply get used to the concept and usage of tell blocks.

OK, let’s play a little bit with your iTunes. This will work best if you have some tracks and playlists already, but don’t worry too much if you don’t. Start off typing this:

tell application "iTunes"
	name of playlist 1
end tell

We are doing nothing more here than finding the name of your first library. Remember that name is a property of the class playlist. This line is simply telling iTunes to give us the name of the first library, and it should return “Library.” Your first playlist in iTunes is always the main library. Now, change that middle line to this:

duration of playlist 1

You will now see a number in your Results pane; it is the total number of seconds of all the tracks (songs) in your entire iTunes library. Remember that duration is another property of the class playlist. Let’s now use a variable and do some math. Change your middle line to this:

set all_Songs to duration of playlist 1

When you run the script, you get the same number in your Results pane. The only difference is that we know that this number is now assigned as a variable named all_Songs. With that variable, we can do anything we want, so add a line right at the end of the script, outside the tell block:

all_songs / 60

When you compile this, all_songs should be changed immediately to all_Songs, and the number you get when you run the script is now the total number of minutes for all your songs. Note here that even though the variable was set and defined inside of the iTunes tell block, AppleScript will be able to use that information outside the tell block as well. This is almost always the case, depending on the type of data you have assigned to your variable. So long as it is basic data, like a number or a string, or a list of numbers and strings, you are just fine accessing that information outside of the tell block. However, if you have assigned some sort of class related data to a variable, it must only be referenced and processed within the tell block, since only there will the key words be recognized.

OK, try adding one more division to our all_Songs variable:

all_Songs / 60 / 60

Of course, now you get the total duration of every track in your library in hours. Depending on how many songs you have in your iTunes Library, this number may be pretty close to what your iTunes pane has listed along the bottom, so check it out. (If you need to go to days, just add a / 24 to the last part of that line.)

I know this has been a long read, so only one more thing before we go. Remember how the dictionary for iTunes said that a playlist’s name is NOT read only? Try this script out for size:

tell application "iTunes"
	set name of playlist 1 to "Top Shelf"
end tell

Now, go over to your iTunes application, and see what happened. Your entire Library has a new name! Can you feel the power? AppleScript gives you some real freedom of expression over a lot of parameters in many of your applications. Spend some time playing with playlists and tracks. Try to read the r/o properties, and try changing some of the other ones. We will end today’s session with a short script that you should try to understand.

Until next time:

tell application "iTunes"
	set all_Playlist_Names to the name of every playlist
end tell

Coming Next: AppleScript Tutorial for Beginners III - The Power of Lists