示例工程 20-error-handling

20-error-handling/03-xpcall-traceback/main.lua

lua · 0.6 KB

-- @runtimes lua54 luajit
--- 演示:xpcall + debug.traceback 保留栈。
local M = {}
 
local function inner()
	error("deep failure", 0)
end
 
local function outer()
	inner()
end
 
--- @return table { ok = boolean, has_traceback = boolean }
function M.run(log)
	log = log or print
	local ok, trace = xpcall(outer, debug.traceback)
	local has_traceback = not ok and trace:find("stack traceback", 1, true) ~= nil
	log(("ok=%s traceback=%s"):format(tostring(ok), tostring(has_traceback)))
	return { ok = ok, has_traceback = has_traceback }
end
 
if not ... then
	M.run()
end
return M