Tricks with lists

Lists, like most other lingo 'Objects', are passed by reference, not by value. This means when you 'set a variable to a list', you are actually assigning a pointer to the list. For example:

a = ["foo"]

b = a

put b

-- ["foo"]

b.append("bar")

put a

-- ["foo", "bar"]

In this example, both 'a' and 'b' contain references to the same list: The list referenced by variable a contains the value "bar" even though we appended "bar" to the list referenced by 'b'. Compare this to strings, for example:

a = "foo"

b = a

put b

-- "foo"

b = b & "bar"

put a

-- "foo"

In the case of strings (as well as integers and floats), when you assign the data to the second variable, Director helpfully assigns a copy of the data to the second variable (I say 'helpfully' since most of the time, especially with numbers, you want to work with copies).

Some data types are passed by reference but most of their methods return copies which may be a little confusing. Consider rects and points, which are 'special' kinds of lists:

a = rect(10,10,100,100)

b = a

b.right = 200

put b

-- rect(10, 10, 200, 100)

put a

-- rect(10, 10, 200, 100)

This demonstrates that rects are passed by reference. However, methods like offset() and inflate() return copies of the rect (they do not modify the original rect):

a = rect(10,10,100,100)

a.offset(10,10)

put a

-- rect(10, 10, 100, 100)

put the result

-- rect(20, 20, 110, 110)

Now sometimes you want to pass strings and numbers around by reference (so that when the string is modified in one place, this change is noted elsewhere). Other times, you might want to inflate or offset rects and have this change reflected elsewhere. In both cases, the trick is to place your data in a list and pass this list.

For example, say you have a score thats calculated in one script (called "GameScore") and various other scripts want to access it. If you put the score into a list and when the movie starts up, esure that the GameScore scripts gives all the other scripts a reference to this list envelope. From then on, the GameScore can change the value stored in the list and any other scripts with a reference to the list will have access to the same data. For example:

info = [#Name: "Luke", #score: 0]

display = info

info[#score] = 1

put display

---- [#name: "Luke", #score: 1]

Another advantage of using lists like this is that you can save on memory use. Imaging a variable called 'WarAndPeace' contains a large amount of text. Every time you assign another variable to the text (such as parameter or local variable in a function to manipulate the text), you are creating another copy of all the text. For short strings, it is not such an issue (not much memory required, and not too much time for Director to make the copy). but for larger strings or where you are trying to squeeze out the maximum framerate, then consider putting the string into a list.

First published 31/03/2006