示例工程 23-gc-and-weak-tables

23-gc-and-weak-tables/02-weak-cache/main.lua

lua · 0.6 KB

-- @runtimes lua54 luajit
--- 演示:弱值表在无强引用后被清理。
local M = {}
 
--- @return table { present = boolean, collected = boolean }
function M.run(log)
	log = log or print
	local cache = setmetatable({}, { __mode = "v" })
	do
		local object = { value = 42 }
		cache.object = object
		log(("present=%s"):format(tostring(cache.object ~= nil)))
	end
	collectgarbage("collect")
	collectgarbage("collect")
	local collected = cache.object == nil
	log(("collected=%s"):format(tostring(collected)))
	return { present = true, collected = collected }
end
 
if not ... then
	M.run()
end
return M