lua-users home
lua-l archive

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

>>>Date: Fri, 17 Sep 2010 21:31:05 -0300
>>>From: Andre Leiradella <>
>On 16/09/2010 18:58, wrote:
>> -------- Original Message --------
>> Subject: Re: Lua GC
>> From:<>
>> Date: Thu, September 16, 2010 2:49 pm
>> To:
>>>>> Andre Leiradella<> wrote:
>>> Hi All,
>>> Given the following script held in a get_t.lua file:
>>> ----------8<----------
>>> local t = {
>>> -- Initialization of fields in t.
>>> }
>>> -- Code that manipulates fields in t.
>>> return t
>>> ----------8<----------
>>> and the following main.lua file:
>>> ----------8<----------
>>> local t = loadfile( 'get_t.lua' )()
>>> -- Use t.
>>> -- Code that runs for a long time and that doesn't
>>> -- reference t anymore follows...
>>> ----------8<----------
>>> Can I count on t being garbage-collected, and also the bytecode
>>> generated by loading get_t.lua along with all local variables and
>>> functions declared in it? Consider that main.lua will be creating
>>> tables, strings and userdata so the GC will be triggered eventually.
>>> I'm aware of require and stuff but since the results of get_t.lua will
>>> be used just once I don't want it to be lying around while main.lua runs.
>>> Thanks,
>>> Andre
>> Table t will not be garbage-collected (unless there is some optimizer
>> magic I don't know about). t is in scope throughout the main file, and
>> will not be dereferenced until main.lua terminates.
>Sure, I overlooked it when I typed the code. The point is, given t will 
>be available for garbage collection, will the GC collect get_t.lua's 
>script from memory? I could say yes from your post, but you didn't say 
>it out loud.

<--- snip --->

Sorry I wasn't clear about it. Anyway, the short answer is "Yes."

Long answer: Actually, the script code will be collected independent of
using t in main.lua. Keep in mind that loadfile() turns the text script
into a function. There isn't anything special about it being a script vs
a function defined by some other means.

Here's what happens:

1. loadfile( 'get_t.lua' ) compiles the script and places an anonymous
function on the stack.
2. The function is called via the parens () on that same line.
3. That function returns t, and t copied into the "local t" of main.lua.
4. When that line completes, the function is popped off the stack.

At this point the function is no longer referenced. It and it's bytecode
are ready to be garbage collected.

OTOH, if your concern is about the reliability of Lua's GC, I don't
think that is an issue.

Hope that makes more sense.

John Giors
Independent Programmer
Three Eyes Software