2016-12-14 84 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