垃圾收集器收集死物体时会做什么

  • 本文关键字:收集器 lua
  • 更新时间 :
  • 英文 :


请按照我的输入注释(使用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);

最新更新