Search code examples
actionscript-3for-loopflashdevelop

simple for loop // but strange output answer


I'm trying to understand why the output for z is always -1 whenever I trace the variable. I'm counting coins and I'm trying to set up a for loop, however, I'm always prompted by an error because of z = -1.

for (var z:int = coins.length; z >= 0; z--);
{
   trace(z);
   trace(coins.length);
}

The output answer I get for these two variables are:

Z = -1
coins.length = 3

Why is this the case? Because all I'm seeing on the output box is:

-1
-1
-1
-1
-1
-1
keeps repeating

If we were to go by the for loop logic, shouldn't the variable z be like this instead?

2
1
0

What can be wrong?


Solution

  • There's your problem:

    for (var z:int = coins.length; z >= 0; z--); // the semicolon at the end.
    

    With the semicolon, the loop ends. You wrote a loop without a body. That's perfectly valid and executes just fine.

    After the loop, the following code is executed once:

    {
       trace(z);
       trace(coins.length);
    }
    

    z is -1, because that's its last value in the loop which causes the loop to stop executing. coins.length never changed and has a value according to the array.

    If we were to go by the for loop logic, shouldn't the variable z be like this instead?

    2
    1
    0
    

    No, because it starts at 3, not 2.