|
|
FrozenHaddock Tutorials: For Loops This tutorial bought to you by Foundation-Flash
Hello and welcome. Today we shall be leaning about one concept of Flash, for loops. For loops are very useful for looping through lots of information quickly, or trying out lots of possibilities quickly. The downside of for loops is that you have to know how many times they are going to run - if you want to do something exactly 10 times for instance. They are also very useful when working with arrays. For loops are very simple to use, as they have a built in counter, so the loop knows how many times it has repeated. You write the for statement using the following basic format: for (init; condition; update) { You must supply three expressions to a for statement: a variable that is set to an initial value, a conditional statement that determines when the looping ends, and an expression that changes the value of the variable with each loop. 'i' is commonly used as the variable, as it stands for iteration which means "a run-through". The condition is if "i <" or "i >" generally; the update is generally i++ (add 1 to i) or i-- (deduct 1 from i). The order of things means you may have to play around with things before you get the loop you want. This is the loop: initialise --> check condition --> do the stuff --> update --> check --> do the stuff etc. For example, the following code loops five times. The value of the variable i starts at 0 and ends at 4. var i; In the previous example, the first expression (i = 0) is the initial expression that evaluates before the first iteration. The second expression (i < 5) is the condition that you check each time before the loop runs. The third expression (i++) is called the post expression and is evaluated each time after the loop runs. If you wanted to run the previous example, you could also use: for (var i = 0; i < 5; i++) { As you can see, the var has moved. In fact you could also have: var a = 0; If you wanted. A could be set to something interesting, like the width of something, or the number of bullets you have fired. Well done, you have slogged it out to the end of this important-but-not-interesting tutorial. Well done!
Harry at Foundation-Flash.com
|
|