Flash 8 Looping Functions
- For loops can define iterative processes using a counter variable and a conditional test. The following sample ActionScript 2.0 code demonstrates:
var a;
for(a=0; a<10; a++) {
trace(a);
}
When execution first enters the loop, the counter variable is set to zero. The conditional test specified as the second item in the loop's opening line then executes. The body of the loop will only execute when the counter variable is still less than 10. Each time the body of the loop executes, it writes the counter value out, then increments it, as specified by the third item in the loop introduction. The body of the loop could contain several lines of processing, this example is purely for demonstration. This loop will iterate 10 times. - While loops can implement iterative functions using slightly different processing than with for loops. The following sample ActionScript demonstrates:
var b=0;
while(b<10) {
trace(b);
b++;
}
This loop also uses a counter variable, which takes part in the conditional test determining whether the loop body executes. The code initializes the counter to zero before the loop starts. When execution reaches the loop, the conditional test is carried out. The loop body will only execute while the counter is less than 10. The loop outputs the counter value and increments it on each iteration. - Rather than dictating the number of times a loop will execute as part of the initial loop statement, ActionScript functions can create infinite loops. Inside an infinite loop, the code must explicitly break at some point or the script may crash. The following sample code demonstrates:
var c=0;
for(;;) {
if(c>=10) break;
else {
trace(c);
c++;
}
}
This code initializes the counter before the loop, then the loop body begins executing straight away as there are no conditions on it. Inside the loop, the code carries out a conditional test. If the counter has reached a value of 10, the loop is exited explicitly. Otherwise the counter value is output then incremented, then the loop begins again. - While loops in ActionScript can also use infinite structures. The following sample code demonstrates:
var d=0;
while(true) {
if(d>=10) break;
else {
trace(d);
d++;
}
}
The body of the infinite while loop carries out the same steps as the infinite for loop, in fact the flow of execution is the same for both. If you are creating infinite loops in your Flash scripts, make sure you have added a break statement at some point, otherwise your loops will never exit.