Learning Flash Lite 1.x ActionScript |
|
|
|
| Flash 4 ActionScript Primer > Emulating arrays | |||
Arrays are useful for creating and manipulating ordered lists of information such as variables and values. However, Flash Lite 1.1 does not support native array data structures. A common technique in Flash Lite (and Flash 4) programming is to emulate arrays with string processing. An emulated array is also called a pseudo-array. The key to pseudo-array processing is the eval() ActionScript function, which lets you access variables, properties, or movie clips by name. For more information, see Using the eval() function.
A pseudo-array typically consists of two or more variables that share the same base name, followed by a numeric suffix. The suffix is the index for each array element.
For example, suppose you create the following ActionScript variables:
color_1 = "orange"; color_2 = "green"; color_3 = "blue"; color_4 = "red";
You can then use the following code to loop over the elements in the pseudo-array:
for (i = 1; i <=4; i++) {
trace (eval ("color_" add i));
}
In addition to letting you reference existing variables, you can also use the eval() function on the left side of a variable assignment to create variables at runtime. For example, suppose you want to maintain a list of high scores as a user plays a game. Each time the user completes a turn, you add their score to the list:
eval("highScore" add scoreIndex) = currentScore;
scoreIndex++;
Each time this code executes, it adds a new item to the list of high scores and then increments the scoreIndex variable, which determines each item's index in the list. For instance, you might end up with the following variables:
highScore1 = 2000 highScore2 = 1500 highScore3 = 3000
|
|
|
|