示例工程 16-call-and-tostring

16-call-and-tostring/03-close-attribute/main.lua

lua · 0.4 KB

-- @runtimes lua54
--- 演示:__close 在离开作用域时清理资源。
local M = {}
 
--- @return table { closed = boolean }
function M.run(log)
	log = log or print
	local closed = false
	do
		local g <close> = setmetatable({}, {
			__close = function()
				closed = true
				log("closed")
			end,
		})
		assert(g ~= nil)
	end
	log(("closed=%s"):format(tostring(closed)))
	return { closed = closed }
end
 
if not ... then
	M.run()
end
return M