lua-users home
lua-l archive

Re: Closures

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Jack Christensen wrote:
>
> I'm getting some results I was not expecting with this code.
> 
> functionList = {}
> 
> for i=1, 10 do
> functionList[ i ] = function()
> print( i ) 
> end
> end
> 
> for i=1, 10 do
> functionList[ i ]()
> end
> 
> I get ten 10's printed out. As I understand closures I would have 
> expected 1 to 10.
Why 1 to 10? You've created ten closures, right. But alll reference
the same i. What's the value of i at the time you call the closure?
You get your expected behaviour (freeze the value at closure creation
time) with this:
for i=1, 10 do
 local i=i -- for each closure a private 'i'
 functionList[ i ] = function()
 print( i ) 
 end
end
Ciao, ET.

AltStyle によって変換されたページ (->オリジナル) /