AS3.0 Reversed for loop

Today I came across an easy mistake to make when new to AS3.

I set up a for loop, to count backwards through an Array. But for some strange reason the loop was never terminating! It was simple, here's the original code

Actionscript:
  1. var i:uint;
  2. for( i=arr.length-1; i>=0; i-- )
  3. {
  4. }

The mistake was simple, I had set i as a uint, so it could never go below 0, so just had to make i an int. It sounds stupid once you realise it, but it wasted enough of my time!

8 Comments so far

  1. Unformatt / August 16th, 2007 11:31 pm

    There was no runtime error?

  2. Zokdok / August 19th, 2007 12:39 pm

    Wouldn't this be shorter? Or doesn't this work in AS3?
    I find this very easy to read also.

    for (var i:uint = arr.length; i-- > 0; )
    {
    // code
    }

  3. Iwan Nagag / August 22nd, 2007 3:35 pm

    @Zokdok,

    Wouldn't this be shorter?
    for (var i:uint = arr.length; i-- >0;) { // code, preferably all on one line }

    This code could be made even shorter if you use the variable name 'a' instead of 'arr' for the array. After all, you wasted two characters there. Also, don't put in comments. They just take up valuable space.

    It is very important to make your code shorter. That way it is harder for other people to understand, harder to debug, and it will run faster.

  4. gabriel / September 13th, 2007 8:40 pm

    @unformatt: There was a script timeout, which doesn't make it immediately obvious where the error is...

  5. Zokdok / September 14th, 2007 12:31 pm

    @Iwan Nagag

    Thank you for the genuine input, I'm going to mount it on my wall. You must be a syke major to come up with a response like that.

  6. sex video / November 25th, 2007 12:07 pm

    Thanks

  7. kzm / March 7th, 2008 5:35 pm

    it's only a matter of taste but i always preferred to loop this way..

    var i:uint = arr.length;
    while( i-- > 0 ){
    trace(i);
    }

  8. gabriel / March 10th, 2008 9:36 am

    that would still break if you are accessing the items within an array (0 > length-1)

Leave a reply

*
To prove that you're not a bot, enter this code
Anti-Spam Image