lua-users home
lua-l archive

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


Egor:

On Thu, May 30, 2019 at 7:39 AM Egor Skriptunoff
<egor.skriptunoff@gmail.com> wrote:
> 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 took the middle road, could not find an explicit afirmation of it
anchoring them, so I assumed they would not, and coded for that.

> I believe that many programmers stumble upon this while learning Lua.

Well, it is a very strange thing to hit, you need to do some weird
things, starting by clearing the "local" which holds it inside the
function. I just got to it because I was being defensive.

> 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.

I assume you mean "f" by "function value".

> 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.

You should add "they are assigned to the arguments, so if these
references are cleared..."

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

This may lead to confussion, unless decorated with some example like
mine above. And, in my opinion, in does not matter too much in pure
lua code ( unless you have some __gc with lua observable side effects
).

Francisco Olarte.