lua-users home
lua-l archive

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


On 13/07/2010, at 6:44 AM, Javier Guerra Giraldez wrote:

> let's try:
> 
> function f()
>  return function () end
> end
> 
> 
> v1 = f()
> v2 = f()
> 
> print (v1 == v2)
> => false
> 
> 
> local function g() end
> function f() return g end
> 
> v1 = f()
> v2 = f()
> print (v1 == v2)
> => true
> 
> 
> -- 
> Javier

Thanks Javier.  I thought I should write a test to work it out, but I didn't come up with anything, certainly not that simple.


On 13/07/2010, at 6:48 AM, Henk Boom wrote:

> Yes. It's semantically different as well: in the first case a setfenv
> on one of the returned functions would not affect the others, since
> they are all separate objects, but in the second case setfenv would
> affect them all, since they are all the same object.
> 
>    henk

That makes sense too.

Thanks everyone!  So here's the test I could have written from the start, now that it's obvious:

local function g() end
local function f() return g() end
for i = 1,10000000 do f() end
print(collectgarbage('count'))

$ time lua closure-test-1.lua 
28.810546875

real	0m0.987s
user	0m0.980s
sys	0m0.004s


local function f() return function() end end
for i = 1,10000000 do f() end
print(collectgarbage('count'))

$ time lua closure-test-2.lua 
41.5634765625

real	0m2.850s
user	0m2.841s
sys	0m0.004s


Cheers,
Geoff