Hey guys,
I hit a confusing bug in my application, but after discovering what it was, I began to wonder if it's a bug with Haxe.
There are two different structures for for loops (coming from C#, I still call them "for" and "foreach" loops. With the standard for loop, one can edit the values of the loop object just fine. When modifying values in a "foreach" structure, however...
There is no syntax error or crash when modifying a value. In fact, we can use the modified value as long as we're still inside the loop. As soon as the loop ends, however, the objects are reverted to their original state.
var editMe:Array<Int>;
editMe = [1, 2, 3, 4, 5];
for (i in 0...editMe.length)
editMe[i] *= 10;
trace(editMe); // Expected: [10,20,30,40,50] | Actual: [10,20,30,40,50]
editMe = [1, 2, 3, 4, 5];
for (i in editMe)
{
i *= 10;
trace(i); // Prints 10, 20, 30, 40, 50, so we are, in fact, modifying the values.
}
trace(editMe); // Expected: [10,20,30,40,50] | Actual: [1,2,3,4,5]
To make matters more confusing, we can add and remove elements from the loop object in both structures, and the changes persist beyond the scope of the loop.
editMe = [1, 2, 3, 4, 5];
for (i in 0...editMe.length)
if (editMe[i] == 3)
editMe.remove(editMe[i]);
trace(editMe); // Expected: [1,2,4,5] | Actual: [1,2,4,5]
editMe = [1, 2, 4, 5];
for (i in editMe)
if (i == 3)
editMe.remove(i);
trace(editMe); // Expected: [1,2,4,5] | Actual: [1,2,4,5]
Is this really counter-intuitive or is it just me?