Lua: Weak Tables

From Mario Fan Games Galaxy Wiki
Revision as of 09:07, 1 April 2010 by Xgoff (talk | contribs) (Created page with '{{Lua}} '''Weak tables''' are how Lua implements ''weak references'', a way of allowing the garbage collector to collect objects that would otherwise …')
(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.

Weak tables are how Lua implements weak references, a way of allowing the garbage collector to collect objects that would otherwise be uncollectible due to residing in a table.

Normally, you might put some object into a table because it is easy to access later on when you need a few other variables to reference it. But, because the table itself references that object, it will not be collected even when none of those variables reference that object anymore: this could cause unneeded memory usage (though not a true memory leak as it is still possible to get the memory back). Often you may be able to delete that entry from the table yourself, but this would require you to essentially babysit the table, and sometimes that reference is never exposed to you. By making this table weak, this problem can be avoided.

Tables can have weak keys or weak values (or both); which of these you need depends on how your table is used. Using a metatable with a __mode field set to "k", "v", or "kv" determines if the keys and/or values are weak. You must define __mode before or within the setmetatable call; if done afterwards by using getmetatable, the resulting behavior is undefined.

When checking if objects are collectible, the garbage collector will treat weak references as though they don't exist. When only weak references (or no references) point to an object, it will be collected.

The following example shows basic use of weak references:

weaktable = {
	some_instance = function () end,
	another_instance = function () end,
}
setmetatable(weaktable, { __mode = "v" }) -- give table weak values

strong = weaktable.some_instance -- we're still using this one!

collectgarbage() -- simulate an eventual collection

print(
	type(weaktable.some_instance),   --> survived ("function")
	type(weaktable.another_instance) --> collected ("nil")
)

As shown, weak references are useful when you are using objects that are meant to be reused, such as in object-oriented models.

Don't forget, only certain types of values are collectible!