Lua: Garbage Collection

From Mario Fan Games Galaxy Wiki
Revision as of 07:36, 1 April 2010 by Xgoff (talk | contribs) (Created page with '{{Lua}} '''Garbage collection''' is how Lua implements memory management, as it does not provide raw access to memory. Garbage collection is needed to reclaim used memory when ce…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Lua
Lua.gif
Basics
Intermediate
Advanced
XLua
Add to this template
 Standardwikimessagebox.png This article assumes the use of Lua 5.1.

Information may not be accurate or may need revision if you are using a different version.

Garbage collection is how Lua implements memory management, as it does not provide raw access to memory. Garbage collection is needed to reclaim used memory when certain pieces of data are no longer referenced, or are referenced only weakly. It also has no problem dealing with cyclic references, which are a problem for some other automatic memory schemes.

Lua's garbage collector has the advantage of it being impossible to truly leak memory. However, unless an object falls out of scope or has only weak references, the garbage collector can't assume it's no longer needed; therefore, you still need to manage those objects yourself.

The garbage collector runs periodically, and frees memory a little at a time; although this means it can take a while for some objects to be deleted, it has much less of a performance impact than full collections. Through the collectgarbage function you can:

  • Stop the collector
  • Restart the collector
  • Force a full collection, or a single cycle
  • Adjust the collector's "step" size and how often it runs relative to memory allocation
  • Retrieve Lua's memory usage (in kilobytes)

An example (printed values may vary):

print(collectgarbage("count")) --> get inital memory usage in kb: 62.1591796875

b = { }
for i = 1, 10000 do b[i] = i end -- generate a large table

print(collectgarbage("count")) --> 318.2197265625

b = nil -- delete the table

collectgarbage() -- force a full collection to make sure the discarded table is collected

print(collectgarbage("count")) --> 56.9384765625

It may be a good idea to run a full collection cycle whenever you can afford it, such as when a game is first paused or right after it loads a new level.