Bug in scope of FOR loop
-
I found this really annoying bug in FOR loops, consider:
function test1(){ for(var index = 0; index < 5; index++){ test2(index); } } function test2(){ Console.print(index); } test1();
Which outputs:
Interface: 0 Interface: 1 Interface: 2 Interface: 3 Interface: 4
Which is not correct in normal Javascript and i can't imagine this is desired behaviour. The variable index should not be in the scope of test2(). This caused for some real strange behaviour in my code, because i'm using a variable with the same name. Besides the issue of the variable being accessible, it's apparently by reference... if you set this variable to a new value you mess up the iteration of your loop in test1(). It took me quite some time to figure out what is causing this weird behaviour...
-
@bastiaan I know I keep saying this, but HISE Script is not Javascript :p
Try this
inline function test1(){ local index; for(index = 0; index < 5; index++){ test2(index); } } function test2(){ Console.print(index); } test1();
-
@d-healey said in Bug in scope of FOR loop:
I know I keep saying this, but HISE Script is not Javascript
I understand your point, but i didn't expected such elementary behaviour to differ from Javascript. But thank you for pointing out the local keyword. That indeed solves my problem. As Javascript developer this is kind of mind f*ckery to my mind 8)
-
@bastiaan Yeah if you come across my old posts from a couple of years ago you'll see I had the same shock :p
-
@d-healey hahahahaha