AS3 – For loop gotcha
April 16th, 2009I knew the compiler moved variable declarations made in a for loop outside of the loop, but I’ve never come across a situation where that mattered. Rather I just enjoyed the fact that it made things run faster, and allowed me to maintin legible code. However, I have come across a situation where this does matter. Because the declarations are moved out side, values will carry over between each iteration. We can see this in the following code:
This will trace out the numbers 1-10, despite the fact that int’s have a default value of 0. So when does this matter? If you have a situation where a variable may or may not be set, after the it is initially set, it will never null. For example:
In this is piece of code (please don’t actually code like this) myObject will always exist, so doSomething will always execute. The solution is very simple, just declare it with a null value like so:
Anyways, I thought it was worth documenting, hopefully doing so saves somebody some head scratching.