2016-12-14 181 views
1

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

我想表在tablenil分配table后会删除weakvalues[1]

+0

'v'是价值。但在你的情况下,你需要'k'我认为 – moteus

+0

@moteus''k''是弱键... – Hydro

+1

对不起。你是对的 – moteus

回答

2

您的代码不会收集垃圾。 试试这个代码

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

这意味着我必须手动c-g,对吧?为什么也叫它两次呢?它只用一个电话就可以工作。 – Hydro

+1

带终结器的值在回收其内存之前需要两个完整的收集周期(第一次循环时调用它们的__gc元变量,第二次运行时释放内存)。大部分时间都不需要它(有时清理“无法访问”的对象是不够的),但它以某种方式卡住了...... – siffiejoe