垃圾收集器收集死对象时会做什么?

时间:2016-12-14 13:03:42

标签: lua

请按照我的输入评论(使用Lua 5.3.2 JDoodle):

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]table分配后删除nil

1 个答案:

答案 0 :(得分:2)

您的代码不会调用collect garbage。 试试这段代码

local t = {}
local weakvalues = setmetatable({t},{ __mode = 'v'})
t = nil
collectgarbage() collectgarbage()
print(#weakvalues);