lua-users home
lua-l archive

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


>>> Andre Leiradella <andre@leiradella.com> 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.

However, there is a very simple solution. Just change your main.lua to
this:

----------8<----------
local t = loadfile( 'get_t.lua' )()

-- Use t.

t = nil     --This will dereference t.
            --You could also call collectgarbage("collect")

-- Code that runs for a long time and that doesn't
-- reference t anymore follows...
----------8<----------

An alternative is to package the operations on t into a function, which
I find "cleaner" (please excuse any typos!):

----------8<----------
local function init()
    local t = loadfile( 'get_t.lua' )()
    --Use t.
    --optional collectgarbage("collect")
end

init()

--Rest of main. t is not in scope.
----------8<----------

John Giors
Independent Programmer
Three Eyes Software
jgiors@ThreeEyesSoftware.com
http://www.ThreeEyesSoftware.com