lua-users home
lua-l archive

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


Sean:

On Thu, May 30, 2019 at 8:16 AM Sean Conner <sean@conman.org> wrote:
> It was thus said that the Great Egor Skriptunoff once stated:
...
> > Lua doesn't anchor function arguments, and this fact may indeed be not
> > obvious from the Lua manual.
...
>   I can't seem to produce this behavior, but I must admit, I can't fathom
> how to trigger it.  I tried the following:
>
>         (function(...)
>           for _ = 1 , 100 do
>             collectgarbage('collect')
>           end
>           print(...)
>         end)(io.open(arg[0]))
>   I run this, and 'nil' is NEVER printed.  The open file value is never
> closed before the function returns.  This code works in Lua 5.1, 5.2, 5.3
> and 5.4 (latest work version).

What Egor and I were talking is about the args not being anchored
EXCEPT by the "locals" defined by the parameters. I'm not sure of the
actual implementation but "..." keeps all the args inside accesible,
so you can get at the file at any time.

I was thinking on something along the line of "function(x) x=nil;
collectgarbage('collect') end". X is the only thing alive, so when I
do something similar to your example from C ( lua_pushfunction,
lua_pushuserdata_with_gc, lua_pcall )  the gc for the userdata may
have been called just after return. I was doing a silly thing,
accessing things which I had put into the ( now inaccessible )
userdata via C-data I had stashed in the Cfunction ( the same C-data
used to build the userdata, AAMOF ), and it hit me that as no
reference was kept anywhere it may have been GCed even if hadn't call
_gc on the CC side ( I accessed it immediately after pcall return, on
the C side ) as someone may have cleared the references in the lua
arguments and called collectgarbage ( I did it erroneously thinking
that some sort of "call frame" would have kept them alive, and as I
did not call collectgarbage before accessing them they may be
collectable, but not collected ).

>   -spc (So how does one see this behavior?)

( Do not use ..., you cannot set ...=nil so the arguments are
referenced by whatever implements ... )

( I should have done this first thing, still not sure if it proves my
point or C api keeps something, but better code around)
[ tmp]$ cat tstgc.lua
-- Is lua keeping arguments alive?
collected=false
mt = {__gc=function() print("Collecting"); collected=true; end}

function bmf(x)
   print("BMF start");
   x=nil
   collectgarbage('collect');
   print("BMF end");
end

print("Starting")
bmf(setmetatable({},mt));
print("Ending")

[ tmp]$ lua tstgc.lua
Starting
BMF start
Collecting
BMF end
Ending
[ tmp]$ lua -v
Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio

Francisco Olarte.