Creating a function within a loop (pointers?)

Posted by user352151 on Stack Overflow See other posts from Stack Overflow or by user352151
Published on 2010-05-27T16:06:01Z Indexed on 2010/05/27 16:11 UTC
Read the original article Hit count: 110

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.

© Stack Overflow or respective owner

Related posts about flash

Related posts about actionscript-3