[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: Lua GC
- From: <jgiors@...>
- Date: Thu, 16 Sep 2010 14:58:52 -0700
> -------- Original Message --------
> Subject: Re: Lua GC
> From: <jgiors@threeeyessoftware.com>
> Date: Thu, September 16, 2010 2:49 pm
> To: lua-l@lists.lua.org
>
> >>> 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<----------
I made a mistake in that second version, it should be:
----------8<----------
local function init()
local t = loadfile( 'get_t.lua' )()
--Use t.
end
init()
--optional collectgarbage("collect") --GC HERE, NOT IN INIT()
--Rest of main. t is not in scope.
----------8<----------
Sorry for any potential confusion.
John Giors
Independent Programmer
Three Eyes Software
jgiors@ThreeEyesSoftware.com
http://www.ThreeEyesSoftware.com