lua-users home
lua-l archive

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


On Apr 29, 2014, at 10:10 PM, Spencer Parkin <spencertparkin@gmail.com> wrote:

> Thanks for the replies.  I'm curious...  how does the algorithm work?  How can Lua determine what does and doesn't need to be collected if it doesn't keep a reference count on an object?
> 
> For example, it's clear that, after the code I had shown earlier is run, that tables A and B are in their own little reference group, but then the same can be said of the table "mytableC = {}" right after it is created.  It's in its own little reference group, yet it shouldn't be garbage collected.
> 
> I should probably buy the book.  I'm starting to vaguely recall the idea of...
> 
> mytableD = {}
> mytableD.refD = mytableD
> mytableD = nil
> 
> ...in reading the book.  Or look at the book online...
> 


There are whole books written about garbage collection, but the basic concept is one of being able to define “reachability”. Lua understands things like global variables and the various locals on the stack. A garbage collect cycle starts at these “well known” locations and walks the graph of all reachable objects (tables, mostly), noting which have been visited. Once this is determined, anything NOT visited is unreachable and is considered garbage that can be collected.

So in your case, although the two tables reference each other, Lua will not reach them since there is no path to them through the reference graph visible to the VM. So they are collected during a GC cycle.

There are of course lots of refinements, such as partial collectors, mark/sweep vs generational designs, etc etc etc. Start in Wikipedia if you want to learn more. But the end result is you don’t have to worry; if your program can no longer access something Lua knows and will eventually vacuum it up.

—Tim