lua-users home
lua-l archive

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




On Monday, September 15, 2014, Paul Bernier <bernier.pja@gmail.com> wrote:
Hello all,

I just noticed an unexpected (to me) behavior of Lua 5.2 and I'd like some enlightenment on it:
for i=0,2 do
    local a = function() end;
    print(a);
end

This code will produce on Lua5.2 something like :

function: 0x20fcc70
function: 0x20fcc70
function: 0x20fcc70

Whereas with Lua5.1 or LuaJIT it'd produce:

function: 0x41e71058
function: 0x41e71078
function: 0x41e71158

My questions are:
-why Lua5.2 has this behavior?
-is there any workaround (other than modifying the VM) to get the second behavior?

Thanks!

In 5.2, Lua will make the optimization of using the same function (closure) reference for two different closures, if they have the same upvalues. 

`i` is not valid outside of the loop. To get the same behaviour, assign `i` to a local, just before the closure. 


for i=0,2 do
    local i_store = i
    local a = function() end;
    print(a);
end


I believe that this will do as you expect, although I'm not at a computer and I'm not sure if Lua 5.2 would optimize this away, or not. 

-Andrew