Skip to main content
Inspiring
June 25, 2008
Question

AS 101 question on loops

  • June 25, 2008
  • 2 replies
  • 169 views
I'm stuck on something that's really fundamental and it's driving me nuts.

I've got five buttons labeled "btn_1", "btn_2", etc. When a button is pressed, I'd like to trace it's corresponding number. When I try this:

for(var i:Number=1;i<6;i++){
this["btn_"+i].onPress = function(){
trace(i);
}
}

... it traces "6" regardless of which button is pressed. I know I'm missing a variable somewhere, but my grey matter's crapped out. Help? Many thanks in advance.
This topic has been closed for replies.

2 replies

bhnhAuthor
Inspiring
June 25, 2008
Awesome. I remember now (anyone see where I left my glasses??).
clbeech
Inspiring
June 25, 2008
yeah this is common with loops of this nature - because the 'last' number iterated to is 6 so the value of i is now 6 once the loop completes. to remedy, store the current value of i in a property of the btn instance then call that prop as in: