References to Containers
Most of the time, containers in a script are used by storing a value directly into a container—or reading a value from one—by simply specifying a variable name (or other container identifier) directly in the script. Sometimes it can be extremely useful, however, to store a reference to a container, which can later be used to access the value of that container. The reference holds the identity of a container rather than its value, and accessing the reference will read or write the contents of the container that it refers to.
Characteristics of References
References have a few characteristics that you will want to be aware of as you work with them. To begin to understand how references work, consider the following example using a reference to a simple variable:
put 32 into age -- Age is now a variable containing the value 32
put a reference to age into yearsOnThePlanet -- Store a reference
put yearsOnThePlanet -- 32 (yearsOnThePlanet refers to age's value)
add 1 to age -- Age is now 33
put yearsOnThePlanet -- Puts 33 (references are dynamic)
In the first line above, a simple value (32) is assigned to an ordinary variable (age). The next line stores a reference to the variable age into the variable yearsOnThePlanet. Now, any access to the value of the yearsOnThePlanet variable will actually be accessing the value of the age variable, as illustrated by the next line of the script, The last two lines of the script increment that value of the age variable and show that the yearsOnThePlanet variable accesses the updated value.
References Bind Tightly
The connection established by a reference is “sticky” (yearsOnThePlanet is glued tightly to age in the above example) so assignments work in the other direction as well — changing the value of either will change the value of both:
put 29 into yearsOnThePlanet
put age -- Puts 29
Reference Syntax
References can be made using the words container, reference, reference to, or refer to, or using the shorthand symbol @ before the container. Or using by reference or as reference after the container. All of the following are equivalent:
put container thing into watcher
set watcher to be a reference to thing
put @thing into watcher
set watcher to reference thing
set watcher to refer to thing
set watcher to thing by reference
set watcher to thing as a reference