lua-users home
lua-l archive

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


It was thus said that the Great Egor Skriptunoff once stated:
> 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."

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

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