Im trying to create a simple loop that creates 50 buttons, adds them to screen and then when a button is pressed, it traces out that number. I can get it to work by doing stuff I consider hacky (such as using the buttons X/Y location to determine its value), but I'd rather just be able to hold a single value in the function.
The code itself is:
for (var a:int = 0; a < 5; a++) {
for (var b:int = 0; b < 10; b++) {
var n = (a * 10) + b + 1;
var btt:SimpleButton = new BasicGameButton();
btt.x = 20 + b * 50;
btt.y = 50 + a * 80;
addChild(btt);
btt.addEventListener(MouseEvent.CLICK, function f() { trace(n); } );
}
}
At the moment, whenever a button is pressed, it simply outputs "50". Is there a way of "freezing" the value of n when the function is created, for that function? (BasicGameButton is just a square button, created in the flash library)
Many thanks.
this is an AS3 flaw comming from the abandoned ECMA-Script draft AS3 is based on ... n
is scoped to the innermost function body it is declared in (thus as if it were declared before the loop), although declared in the innermost loop body of your code.
you can do the following:
var makeFunction:Function = function (n:int):Function {//this can of course also be a method
return function (event:MouseEvent):void {
trace(n);
}
}
//in the loop body, use it like this:
btt.addEventListener(MouseEvent.CLICK, makeFunction(n));
As a side note: Haxe does not have this flaw.