Loops

I l @ ve RuBoard

Loops

Computers are great for doing repetitive tasks. Whereas a human gets bored doing the same thing a few times in a row, a computer is happy to repeat the same task hundreds or even millions of times. In fact, repetitive tasks are where computers really excel.

Looping is an important part of every programming language. ActionScript is no exception. You can repeat a set of instructions a certain number of times, or until a certain condition is met.

In fact, conditions are an important part of looping. All a loop needs is a starting and ending point, plus a condition that signifies the end of the loop.

For instance, if you want to loop 10 times, a variable will be used to start counting at 0. Each time the loop loops, the counter is incremented by 1. When it reaches 9, the loop ends and the program continues past the end of the loop. The following is an illustration of a typical program loop:

  1. Some command before loop.

  2. Start of loop, counter set to 0.

  3. Some command in loop.

  4. Some other command in loop.

  5. Counter incremented by 1.

  6. If counter is less than 9, go back to step 3.

  7. Some command after loop.

In the preceding seven steps, step 1 only happens once. Then step 2 signifies the beginning of the loop. Steps 3, 4, 5, and 6 are executed 10 times. After the 10th time, step 7 is executed, and the program continues from there.

graphics/book.gif

So if the loop is to occur 10 times, why does it check to see whether the counter reaches 9? This is because the counter starts at 0. This is typical of most computer programming languages. The counter counts from 0 to 9 instead of from 1 to 10.


Another important part of loops is when, exactly, the condition is examined. In some cases, it is examined before the commands in the loop are executed, and in other cases it is examined in the end.

There are also ways to break out of loops prematurely, and ways to skip the rest of the commands in a loop and start back at the beginning. We'll look at the ways to do this in ActionScript in Hour 4, "Writing Code in Flash."

I l @ ve RuBoard


Sams Teach Yourself Flash MX ActionScript in 24 Hours
Sams Teach Yourself Flash MX ActionScript in 24 Hours
ISBN: 0672323850
EAN: 2147483647
Year: 2002
Pages: 272

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