lua-users home
lua-l archive

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


On Jul 13, 2010, at 3:32 PM, Eike Decker wrote:

> 2010/7/13 Doug Currie <doug.currie@gmail.com>:
>> 
>> t = {}
>> local a
>> for i = 1, 10 do
>>  a = i
>>  t[i] = function() a = a + 1; return a end
>> end
>> 
>> and this code 10 closures...
>> 
>> t = {}
>> for i = 1, 10 do
>>  local a
>>  a = i
>>  t[i] = function() a = a + 1; return a end
>> end
>> 
>> Another argument against local by default!
> 
> Your code will not work as you expect. All 10 functions share the same
> variable and will operate on the same values. If you want to have
> different variables, there is no way around either objects or
> closures. Why are you afraid of "new" closures?

Sorry to have been cryptic. I am not afraid!

The two versions above do completely different things. In the 1st version all 10 closures share the same variable. The 2nd version does not share the variable among the closures. The difference is in the placement of the local declaration. Hence my (snide) comment about local declarations being very important in this case.

e