lua中的weak table

weakTable = {}
weakTable[1] = function() print("i am the first element") end
weakTable[2] = function() print("i am the second element") end
weakTable[3] = {10, 20, 30}
weakTable[4] = {"4"}
weakTable[{}] = 1
setmetatable(weakTable, {__mode = "kv"})--mode:v,k,vk
collectgarbage()
print("results: "..(#weakTable))
for k,v in pairs(weakTable) do
    print(k,type(v))
end
print(nil == weakTable)
--當mode爲v時 設置表爲value弱引用,只剩weakTable[{}]未被回收
--當mode爲k時 設置表爲key弱引用,weakTable[{}]被回收
--當mode爲kv時,weakTable中元素被回收,weakTable不等於nil
相關文章
相關標籤/搜索