lua-users home
lua-l archive

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


On Mon, May 27, 2019 at 8:26 PM Francisco Olarte wrote:

At first I thought the lua code would keep it alive, as it is in the
arguments of the called function. Then I realized the function could
be "function(ud); ud=nil; collectgarbage(); end". Then I entered a
death spiral of documentation reading trying to find some thing.


Lua doesn't anchor function arguments, and this fact may indeed be not obvious from the Lua manual.
I believe that many programmers stumble upon this while learning Lua.
From the (incorrect but) intuitive point of view, a function invocation "f(x,y)" looks like some sort of instance that holds all its elements (function value and argument values) until the function returns.

But actually the following happens:
   the function value is anchored by Lua VM until the function returns;
   the argument values are not anchored, they are just passed to the function's body, so they may be garbage collected before the function returns.

I suggest to add the following phrase to Lua manual:
"For example, function's arguments may be collected before the function returns."