lua-users home
lua-l archive

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


Mike King wrote:

Can someone tell me why the following code reports two
different function addresses?

function a()
        return function () return b() end
end

function b()
        return a()
end

print(a()())
print(a())

Every time a function expression (an expression of the form
"function(...) ... end") is evaluated, a new function is
created, even if that function would behave identically to
some other function.  (If you don't want this, arrange for
the function expression in question to only be evaluated
once, e.g., by moving it outside of the function it's in.)

In this case, a is called, it returns a function, that
function is called, it calls b, which calls a, which returns
a new function, which is then printed.  Then a is called,
and it returns yet another function, which is printed.

A simpler demonstration of the point made in the first
paragraph:

print(function() end)
function: 0x498f88
print(function() end)
function: 0x499368

--
Aaron