AppleScript Programming/Lists and records

From Wikibooks, open books for an open world
Jump to: navigation, search

For the best results, you should have Script Editor open, so you can test the code and results as you read.

Basics of Lists[edit]

Applescript has two data structures, lists and records. A list is an ordered collection of objects. Ordered, in the sense that items can be retrieved by index, and of objects because you can put anything into a list with anything else.

List creation is simple, anything that you put between a { and a } is a list.

set myList to {} -- make a new list
set myList to myList & {1, "two", {7}, {fred:"barney", wilma:"betty", foo:"bar"}, 5} -- add a bunch of items to the list
set k to {6, "three", {8}, {george:"jetson", elroy:"jetson", judy:"jetson"}, 0}

In the example above we create two lists. The first list l contains 5 items, the number 1, a string "two", a list containing the number 7, a record containing three properties, fred, wilma, and foo with string values, and the number 5.

We can access these items in several ways. The statements

item 3 of myList
third item of myList
myList's third item
myList's item 3

Will all return the same value, {7}, that is, a list containing the number 7.

Looping Through a String As If It Were a List[edit]

This works a character at a time. (Strings are sequences of characters and behave accordingly.)

set my_string to "freedom is not freedom fries"
repeat with counter_variable_name from 1 to count of my_string
	set current_character to item counter_variable_name of my_string
end repeat

Basics of Records[edit]

A record is a list of properties. You can retrieve items from a record by name, but not by index. For example, to retrieve the elroy of the property list {scooby:"doo", elroy:"jetson",grape:"ape"}, I can retrieve it by name.

elroy of {scooby:"doo", elroy:"jetson", grape:"ape"}

Which will return the string "jetson"

but not by index,

item 2 of {scooby:"doo", elroy:"jetson", grape:"ape"}

Which returns an error.