160 Syntax and Language Fundamentals
Using while loops
Use the while statement to repeat an action while a condition exists, similar to an if
statement that repeats as long as the condition is
true.
A
while loop evaluates an expression and executes the code in the body of the loop if the
expression is
true. If the condition evaluates to true, a statement or series of statements runs
before looping back to evaluate the condition again. When the condition evaluates to
false,
the statement or series of statements is skipped and the loop ends. Using
while loops can be
very useful when you aren’t sure of how many times you’ll need to loop over a block of code.
For example, the following code traces numbers to the Output panel:
var i:Number = 0;
while (i < 5) {
trace(i);
i++;
}
You see the following numbers traced to the Output panel:
0
1
2
3
4
One disadvantage of using a while loop instead of a for loop is that infinite loops are easier
to write with
while loops. The for loop example code does not compile if you omit the
expression that increments the counter variable, but the
while loop example does compile if
you omit that step. Without the expression that increments
i, the loop becomes an
infinite loop.
To create and use a
while loop in a FLA file, follow this example.
To create a while loop:
1. Select File > New and then select Flash Document.
2. Open the Components panel and drag a DataSet component onto the Stage.
3. Open the Property inspector (Window > Properties > Properties) and type the instance
name users_ds.