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:
-
var i:uint;
-
for( i=arr.length-1; i>=0; i-- )
-
{
-
}
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
Leave a reply
There was no runtime error?
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
}
@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.
@unformatt: There was a script timeout, which doesn't make it immediately obvious where the error is...
@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.
Thanks
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);
}
that would still break if you are accessing the items within an array (0 > length-1)