示例工程 26-testing-and-lint

26-testing-and-lint/02-error-assertions/main.lua

lua · 0.5 KB

-- @runtimes lua54 luajit
--- 演示:断言错误消息与错误对象。
local M = {}
 
local function parse(value)
	if type(value) ~= "number" then
		error("not a number: " .. tostring(value), 0)
	end
	return value * 2
end
 
--- @return table { ok = boolean, message = string }
function M.run(log)
	log = log or print
	local ok, message = pcall(parse, "x")
	log(("ok=%s message=%s"):format(tostring(ok), tostring(message)))
	return { ok = ok, message = tostring(message) }
end
 
if not ... then
	M.run()
end
return M