示例工程 05-variables-and-scope

05-variables-and-scope/05-const-attribute/main.lua

lua · 0.9 KB

-- @runtimes lua54
--- 演示:<const> 禁止重新赋值,<close> 在作用域退出时清理。
 
local M = {}
 
--- @return table { value = integer, close_called = boolean }
function M.run(log)
	log = log or print
	local value <const> = 42
	local close_called = false
	do
		local guard <close> = setmetatable({}, {
			__close = function()
				close_called = true
			end,
		})
		log(("guard_is_table=%s"):format(tostring(type(guard) == "table")))
	end
	log(("close_called=%s"):format(tostring(close_called)))
	local bad, err = load("local x <const> = 1; x = 2", "=const")
	log(("const_compile_error=%s"):format(tostring(bad == nil)))
	log(
		("const_error_mentions_const=%s"):format(
			tostring(err ~= nil and err:find("const", 1, true) ~= nil)
		)
	)
	return { value = value, close_called = close_called, const_error = bad == nil }
end
 
if not ... then
	M.run()
end
 
return M