A weak table is a table whose elements are weak references. A weak reference is ignored by the garbage collector. In other words, if the only references to an object are weak references, then the garbage collector will collect this object.
A weak table can have weak keys, weak values, or both. A table with weak keys allows the collection of its keys, but prevents the collection of its values. A table with both weak keys and weak values allows the collection of both keys and values. In any case, if either the key or the value is collected, the whole pair is removed from the table. The weakness of a table is controlled by the value of the __mode
field of its metatable. If the __mode
field is a string containing the character '=k=', the keys in the table are weak. If __mode
contains '=v=', the values in the table are weak.
After you use a table as a metatable, you should not change the value of its field __mode
. Otherwise, the weak behavior of the tables controlled by this metatable is undefined.