简介
弱引用table(weak table)是用户用来告诉Lua一个引用不应该阻碍对该对象的回收。所谓弱引用,就是一种会被垃圾收集器忽视的对象引用。
如果一个对象的引用都是弱引用,该对象也会被回收,并且还可以以某种形式来删除这些弱引用本身。
Lua中的GC
弱引用table有3种类型
1、具有弱引用key的table;
2、具有弱引用value的table;
3、同时具有弱引用key和value的table;
table的弱引用类型是通过其元表中的__mode字段来决定的。
这个字段的值应为一个字符串:
如果包含’k’,那么这个table的key是弱引用的;
如果包含’v’,那么这个table的value是弱引用的;
弱引用table中只有对象可以被回收,而像数字、字符串和布尔这样的“值”是不可回收的
例子:文档修饰器
local docstrings = setmetatable({}, {__mode = "kv"})
function document(str)
return function(obj) docstrings[obj] = str; return obj end
end
function help(obj)
print(docstrings[obj])
end
document[[Print the documentation for a given object]](help)
document[[Add a string as documentation for an object]](document)
f = document[[Print a hello message]](
function()
print("hello")
end
)
f()
help(f)