AppleScript Programming/Lists and records

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

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

[edit] Basics of Lists and Records

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 l to {} -- make a new list
set l to l & {1, "two", {3}, {fred:"barney", wilma:"betty", foo:"bar"}, 5} -- add a bunch of items to the list
set k to {6, "seven", {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 3, 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 l
third item of l
l's third item
l's item 3

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

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.


[edit] Looping through a variable as if it was a list

This works a character at a time.

 
set property_is_theft_items to "freedom is not freedom fries"
repeat with beg_borrow_or_steal_as_dependent from 1 to count of property_is_theft_items
	set asylum_is_being_run_by_inmates to item beg_borrow_or_steal_as_dependent of property_is_theft_items
end repeat