[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Creating closures (or not)
- From: Eike Decker <zet23t@...>
- Date: Tue, 13 Jul 2010 21:32:42 +0200
2010/7/13 Doug Currie <doug.currie@gmail.com>:
>
> On Jul 13, 2010, at 8:04 AM, Roberto Ierusalimschy wrote:
>
>>> My guess is that they would only be pooled if they share the same prototype,
>>> and do not use any upvalues, such as:
>>>
>>> t = {}
>>> for i = 1, 10 do
>>> t[i] = function() end
>>> end
>>
>> They may be reused even with upvalues, as long as they have the same
>> upvalues; each prototype caches the last closure created with it.
>
> So, I suppose this code creates one closure...
>
> 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!
>
> e
>
>
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?
Greetings,
Eike
- References:
- Creating closures (or not), Geoff Leyland
- Re: Creating closures (or not), Peter Cawley
- Re: Creating closures (or not), Geoff Leyland
- Re: Creating closures (or not), Javier Guerra Giraldez
- Re: Creating closures (or not), Geoff Leyland
- Re: Creating closures (or not), Pierre-Yves Gérardy
- Re: Creating closures (or not), Roberto Ierusalimschy
- Re: Creating closures (or not), Duncan Cross
- Re: Creating closures (or not), Kristofer Karlsson
- Re: Creating closures (or not), Roberto Ierusalimschy
- Re: Creating closures (or not), Doug Currie