Using Loops to Repeat Actions


Loops are a type of ActionScript that allow sections of code to execute repeatedly. They usually have a counter to keep track of how many times they have looped. When the counter equals a maximum number, the loop stops running.

Having a counter helps avoid infinite loops, which can cause serious problems in the execution of code, including causing a warning box to pop up. The warning indicates that your code is taking up processor resources and asks you whether you would like to stop running the application. Although this doesn't crash your computer, it is a serious error in your application. Other ways to avoid infinite loops is to be sure you have a break, or escape, from the loop when the condition for stopping is met.

As with conditionals, it would be helpful to be familiar with some operators used for creating loops before you start using them. These operators are used to keep track of how many times the loop has been repeated. The ++ operator increments the value of your variable by 1. The += is a shorthand operator that says to add the value to the right of the = sign and return a value. So count+=3 adds 3 and returns the value to be used. The -= operator simply subtracts and returns the value.

Note

It makes a difference whether the ++ appears before the variable (pre-increment) or after it (post-increment). Pre-incrementing says to add 1 now and use that value in the code. Post-incrementing says add 1 the next time it is encountered, and to use its current value for now.


for

The most common type of loop in Flash is the for loop. It enables you to efficiently set up the initial state of a counter, the maximum number of loops, and the amount to increase your loop each time the loop runs. Several other types of loops are available, but this is the one that's used most of the time.

In a for loop, parentheses wrap the initialization, condition, and increment statements all in one compact line. In this example, i is initialized at zero. The loop runs as long as i is less than 20, and i is incremented by one each time the loop is repeated. That leaves the space between the curly braces free to concentrate on the business at hand: the action that is to be repeated. In this case, it traces the value of i to the output window.

The syntax is as follows:

for (initialization; condition; update){     statement1;     statement2; }


For example,

var i:Number;  // declare the counter for(i=0; i<20; i++){     trace(i); }


This is all it takes to make repetitive actions easily accessible in our projects.



Special Edition Using Macromedia Studio 8
Special Edition Using Macromedia Studio 8
ISBN: 0789733854
EAN: 2147483647
Year: 2003
Pages: 337

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net