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.
You don't need to "clear" the locals that hold the parameter values; it's enough to change their value, making the old value then inaccessible and is garbage-collectable at any time after this time, before the function returns, because it is no longer accessible at all (unless you've aliased that value by copying into another variable or data structure which is still accessible).
A typical example :
function(x)
if type(x) = 'string'
x = tonumber(x)
-- x was a string whose value may be gargage collected before this function returns
-- x is now another object, a number
else if type(x) = 'table'
x = average(x)
-- x was a table whose value may be gargage collected before this function returns
-- x is now another object, a number
collectgarbage('collect') -- fhe former table or string value of x may be garbage-collected
local y = dosomethingwith(x)
return y