Subtle loop problem in FMX2004
This is weird and it's such a subtle problem it’s a bit worrying that it can so easily catch you out.
Look at this code
doSomething = function(v){trace("value is "+v);}
var x=0;
var step=10;
for(var i=0;i<1;i++){
doSomething(x)
x+=step
}
so when doSomething is called what is the value of x traced out? Answer is 0....of course!!
Now look at this
doSomething = function(v){trace("value is "+v);}
var x=0;
var step=10;
for(var i=0;i<1;i++){
doSomething(x)
(x+=step)
}
so when doSomething is called what is the value of x traced out ? Answer is 10....??
Because the doSomething call in the loop wasn’t terminated with a ";" and the next line has a pair of brackets "()" round it then that expression gets evaluated before the call is made...hmmmmm
Ok the obvious thing is to code it properly and always use a ";" which I do as a rule, this was just a small slip up as I was testing something and threw the code together (at least thats my excuse. lol)
... but its such a subtle slip up I wonder how many other places have I done this before and run around scratching my head about what the problem was?
Comments
Very interesting? This is still an issue with Flash 8 AS2. I wonder if Adobe will take care of this in AS3?
Posted by: Curtis J. Morley | March 23, 2007 09:44 AM