Jump to content

AppleScript Programming/Lists and records

From Wikibooks, open books for an open world

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 | edit source]

Applescript has two separate classes of data structure that are used to represent a collection of items: the list class, and the record class. A list is an ordered collection of objects, which can be any value or data structure that AppleScript understands. To say that the contents of a list is ordered means that every item in the list occupies a numbered position. This number is termed the item's index, which can be used to retrieve a specific item from a list.

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 | edit source]

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 | edit source]

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.

Next Page: Aliases and paths | Previous Page: Numbers and strings
Home: AppleScript Programming