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

 

posted on 2019-02-01 15:56  魔天天  阅读(167)  评论(0编辑  收藏  举报