请按照我的输入注释(使用jdoodle的lua 5.3.2):
local table = {};
local weakvalues = setmetatable(
{
table
},
{
-- Let weakvalues values
-- be weak, so that they fade when dead objects are g-c.
__mode = 'v'
});
table = _;
-- Now the previously ref. table is unreachable
-- since there are no other references, I think so...
-- Sychronously wait this loop statements
-- in order to execute a next statement (maybe the
-- garbage-collector would have collected the unreachable table above
-- while this loop executes).
for i = 1, 5e7 do end
-- Expected to log 0, but it logs 1. Is the unreachable table
-- still reachable?
print(#weakvalues);
我以为table
处的表格将删除weakvalues[1]
,用nil
分配table
。
您的代码不调用收集垃圾。尝试此代码
local t = {}
local weakvalues = setmetatable({t},{ __mode = 'v'})
t = nil
collectgarbage() collectgarbage()
print(#weakvalues);