Beware of the uint
When Actionscript3 came along - long, long ago -- one of the things I liked the most was the introduction of the uint - unsigned integer - data type.
It makes sense, you know? If you want to iterate over an array, you will never have negative values. Perfect use for a uint.
Most of my programming training comes from Javascript and Lisp. Not to say that's what I've spent the most time coding in, just that those languages have revealed more quirks about programming - and life - to me than any other. So naturally, with my JS background, I prefer to iterate over lists from tail to head when appropriate.
- for( var i:uint = arr.length - 1; i >= 0; i-- )
- _do.stuff( arr[i] );
the reason I like this method more is because you get rid of the extra variable in which you store the length of your array. And, as a side note, please store your array length somewhere when iterating over the array from head to tail! Why bother your CPU with reading a property of an object each time you go through your loop?
You know that Javascript and Actionscript are both ECMAScript, so you can easily carry most of your knowledge from one to the other.
So, the above example is how I'd iterate over an array in Actionscript. Everything was okay in AS2, but things started breaking when I carelessly used the same code in AS3. If you blink, you might miss the reason. That was some years ago, but I recently made the same error.
It took me five minutes of adding breakpoints and stepping through the loop to catch the bug. Funny thing how this was scarred deep in my brain once, and I totally forgot about it. You can imagine how silly and upset I felt when I realized what had happened.
Here's the breakdown. When you take an unsigned integer whose value is zero and subtract 1 from it... you can't get -1. You don't get NaN, either. You don't get and error or warning. What you get is 4294967295 because, for some reason, it takes a full lap around the possible values. In my loop, since i will go from 0 to 4294967295, it will never be -1 which is what I need for the loop to start. Can you say infinite loop and stack overflow?
So, what I did was
- for( var i:uint = arr.length; i-- > 0; )
- _do.stuff( arr[i] );
Of course, I wasted more time and keystrokes to find this elegant solution than it would have taken me to just use an int.
But I still love the uint.



Leave a Comment :