The for Loop

Now let's get into the powerful for loop. You have already had a little taste of how the for loop works, now we can look at what the for loop can really do for you. Get it started, then we can examine what's happening:

  1. First, select the opening brace of the init function - we want the for loop to run at the start of the function
  2. Click Statements > Conditions/Loops > for
  3. Type n=0 in the Init box
  4. Type n<numStars in the Condition box
  5. Type n++ in the Next box

Let's have a look at what each of those arguments are doing:

Init: Init is short for initialize, because it's where you declare the variable you will work with in the for loop. This only happens one time, at the start of the loop. We defined a new variable equal to zero: n=0

Condition: This is just an If Statement. The for loop will check to see if n<numStars (Remember we set numStars equal to 30). If the condition is met, the actions between the braces will execute. If the condition is not met (if n>=numStars), the for loop will quit.

Next: If the Condition is met and the actions in the for loop execute, we tell Flash what we want it to do next: Increment n by 1 (n++). After the increment, the script loops back to the the Condition and checks to see if n is still less than numStars. If it is, the actions inside the braces run again. This is an easy way to make the same actions run exactly 30 times.

Our goal is to get 30 different stars on the stage, and we need each one to have a unique Instance Name so we can control them (if you don't know the Instance Name of a MovieClip, you can't do much to with ActionScript). We can take advantage of that variable n we just created in the for loop, because it's going to equal 0 then 1 then 2 then 3... all the way up to 29.

Select the attachMovie action so we can modify the settings:

  1. New Name will now be "newStar"+n
  2. Select the Expression box because we want Flash to evaluate that variable
  3. Change the Depth to n

Nothing new is going to happen until you get those actions between the for loop braces, but can you see where this is going? "newStar" will always be newStar because it is a string literal (the quotes!). However, n is a variable that will equal 0, 1, 2...29. When we add them together we will be creating instance names of newStar0, newStar1, newStar2...newStar29