Lua: Garbage Collection

From Mario Fan Games Galaxy Wiki
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.

Collectible Types

Not all types will be collected by the garbage collector, however. This slightly complicates use of weak tables, but on the other hand it's less garbage that needs to be collected (and therefore potentially higher collection performance). The following chart shows which types can and cannot be collected:

Collectible
Nil No
Numbers No
Booleans No
Tables Yes
Functions Yes
Threads Yes
Strings Yes1
Userdata Depends2
  1. Strings are stored internally in a pool, and are only collected if that pool is the only reference to that string.
  2. "Full" userdata (C data) are collected, but "light" userdata (C pointers) are not