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.

[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 string as if it was a list

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
Personal tools
Namespaces
Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export