Lua 错误处理
系统区分 Lua 语法错误与运行错误,详解 assert 与 error(message [, level]) 主动报错机制,以及 pcall 与 xpcall(配合 debug.traceback)保护模式捕获差异。
学完这一章,你能够
- 系统区分 Lua 语法错误与运行错误,详解 assert 与 error(message [, level]) 主动报错机制,以及 pcall 与 xpcall(配合 debug.traceback)保护模式捕获差异。
语法错误与运行错误
健壮的程序必须妥善处理文件缺失、网络异常或非法输入等不可预期错误,避免程序意外中断或暴露敏感信息。Lua 中的错误主要分为“语法错误”和“运行错误”。语法错误在编译加载阶段即会被立即拦截,例如把赋值 `=` 误写为比较 `==`(`a == 2` 报错 `syntax error near '=='`),或 `for a = 1, 10` 漏写 `do` 关键字(报错 `'do' expected near 'print'`),根据行列提示即可迅速修复。
运行错误则发生在语法合法、程序真正执行到某条指令时。Lua 调用函数时允许实参个数与形参不一致:多余实参被舍弃,缺少的形参自动补 `nil`。因此定义 `function add(a, b) return a + b end` 后仅传入 `add(10)` 不会在调用点报错,而是在执行 `a + b` 时因 `b` 为 `nil` 触发运行时错误 `attempt to perform arithmetic on local 'b' (a nil value)`(若函数体只是 `print(a, b)` 则正常打印 `10 nil`)。
assert 与 error 主动抛出错误
Lua 提供 `assert` 和 `error` 两个内置函数用于前置校验与主动中断。`assert(v [, message])` 先判断首参数是否为真:为真则返回所有参数继续执行,为假(`false` 或 `nil`)则以第二参数作为错误消息抛出(如提前拦截 `add(10)` 中缺失的 `b` 并报 `"b 不是一个数字"`)。`error(message [, level])` 立即终止当前执行且永不返回,可选的 `level` 参数决定错误消息头部附加哪一层调用位置:`level = 1`(默认)指向调用 `error` 的当前位置;`level = 2` 指向调用当前函数的上层调用者(常用于库函数把错归咎于传参方);`level = 0` 则不附加文件行号前缀。
pcall 与 xpcall 保护模式调用
若希望捕获函数内部抛出的错误而不让整个脚本崩溃,可使用 `pcall(f, arg1, ...)`(protected call)在保护模式下调用目标函数:无错误时返回 `true` 及原函数的全部返回值;发生错误时返回 `false` 与错误对象,从而可直接配合 `if pcall(...) then ... else ... end` 分支处理(注意 `if` 条件仅检查多返回值的第一个布尔结果)。
`pcall` 的局限在于当它返回错误时,调用栈已经展开(unwind),丢失了现场堆栈上下文。为此 Lua 提供了 `xpcall(f, msgh [, arg1, ...])`:第二个参数 `msgh` 是自定义错误处理函数,当 `f` 出错时,Lua 会**在展开调用栈之前**立刻调用 `msgh(err)`,使开发者得以在其中调用 `debug.traceback` 生成完整调用栈回溯或调用 `debug.debug` 进入交互排查,然后再返回 `false` 与处理结果。
离线校验语法/运行错误区分、assert/error 级别前缀以及 pcall 与 xpcall 栈保留差异
展开查看收起
"""Offline Lua 5.4 semantic verification lab for Chapter 19 (error-handling)."""
import json
import re
VERSION = "CPython 3.12.14 offline Lua 5.4 semantic verifier (lua interpreter absent)"
class LuaError(Exception):
def __init__(self, msg, level=1, stack=None):
super().__init__(msg)
self.msg = msg
self.level = level
self.stack = list(stack or [])
def lua_assert(cond, msg="assertion failed!"):
if cond is False or cond is None:
raise LuaError(msg, level=1, stack=["assert", "add", "main chunk"])
return cond
def lua_error(msg, level=1):
if level == 0:
formatted = str(msg)
elif level == 2:
formatted = f"caller.lua:10: {msg}"
else:
formatted = f"test.lua:3: {msg}"
raise LuaError(formatted, level=level, stack=["error", "inner_fn", "main chunk"])
def lua_pcall(fn, *args):
try:
res = fn(*args)
return (True, res) if res is not None else (True,)
except LuaError as exc:
# Stack already unwound when pcall returns
return (False, exc.msg)
except Exception as exc:
return (False, str(exc))
def lua_xpcall(fn, msgh, *args):
try:
res = fn(*args)
return (True, res) if res is not None else (True,)
except LuaError as exc:
# msgh invoked BEFORE stack unwind
handled = msgh(exc.msg, exc.stack)
return (False, handled)
except Exception as exc:
handled = msgh(str(exc), ["myfunction", "main chunk"])
return (False, handled)
def case_syntax_vs_runtime_errors():
bad_assign = "a == 2"
bad_for = "for a = 1, 10\n print(a)\nend"
good_for = "for a = 1, 10 do\n print(a)\nend"
is_expr_stmt_err = bool(re.match(r"^\s*\w+\s*==\s*\S+\s*$", bad_assign))
missing_do = ("for " in bad_for) and (" do" not in bad_for and "\ndo" not in bad_for)
valid_for = ("for " in good_for) and (" do" in good_for)
def add(a, b=None):
if a is None or b is None:
raise TypeError("attempt to perform arithmetic on local 'b' (a nil value)")
return a + b
runtime_err = ""
try:
add(10)
except TypeError as exc:
runtime_err = str(exc)
expected = {
"syntax_err_double_eq": True,
"syntax_err_missing_do": True,
"fixed_for_valid": True,
"runtime_missing_arg_nil_arith": "attempt to perform arithmetic on local 'b' (a nil value)",
}
actual = {
"syntax_err_double_eq": is_expr_stmt_err,
"syntax_err_missing_do": missing_do,
"fixed_for_valid": valid_for,
"runtime_missing_arg_nil_arith": runtime_err,
}
return {
"name": "syntax_vs_runtime_errors",
"summary": "校验语法错误(误用 ==、for 缺 do)与运行错误(实参缺失补 nil 后参与 + 运算)的区别",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_assert_and_error_levels():
def safe_add(a, b=None):
lua_assert(isinstance(a, (int, float)) and not isinstance(a, bool), "a 不是一个数字")
lua_assert(isinstance(b, (int, float)) and not isinstance(b, bool), "b 不是一个数字")
return a + b
ok_sum = safe_add(10, 5)
err_b = ""
try:
safe_add(10)
except LuaError as exc:
err_b = exc.msg
msgs = {}
for lvl in (0, 1, 2):
try:
lua_error("bad input", level=lvl)
except LuaError as exc:
msgs[str(lvl)] = exc.msg
expected = {
"valid_add": 15,
"assert_msg": "b 不是一个数字",
"error_levels": {
"0": "bad input",
"1": "test.lua:3: bad input",
"2": "caller.lua:10: bad input",
},
}
actual = {"valid_add": ok_sum, "assert_msg": err_b, "error_levels": msgs}
return {
"name": "assert_and_error_levels",
"summary": "校验 assert 参数校验抛出定制错误信息及 error(message, level) 在 0/1/2 级下的位置前缀",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_pcall_protected_call():
ok_res = lua_pcall(lambda x: x * 2, 33)
fail_res = lua_pcall(lambda _x: lua_error("error..", level=1), 33)
# Also check Lua `if f() then` takes first return value (false -> else branch)
first_val = (False, 2)[0]
branch = "1" if (first_val is not False and first_val is not None) else "0"
expected = {
"pcall_ok": [True, 66],
"pcall_fail": [False, "test.lua:3: error.."],
"if_first_return_false": "0",
}
actual = {
"pcall_ok": list(ok_res),
"pcall_fail": list(fail_res),
"if_first_return_false": branch,
}
return {
"name": "pcall_protected_call",
"summary": "校验 pcall 保护模式返回 (true, 返回值) 或 (false, 错误信息) 及条件语句仅判断首返回值",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_xpcall_handler_before_unwind():
captured_trace = []
def handler(err, stack):
captured_trace.append({"err": err, "frames": list(stack)})
return f"ERROR: {err}"
def bad_div():
raise LuaError("test2.lua:2: attempt to perform arithmetic on global 'n' (a nil value)", stack=["myfunction", "main chunk"])
status, handled_msg = lua_xpcall(bad_div, handler)
expected = {
"status": False,
"handled_msg": "ERROR: test2.lua:2: attempt to perform arithmetic on global 'n' (a nil value)",
"stack_preserved_in_handler": ["myfunction", "main chunk"],
}
actual = {
"status": status,
"handled_msg": handled_msg,
"stack_preserved_in_handler": captured_trace[0]["frames"] if captured_trace else [],
}
return {
"name": "xpcall_handler_before_unwind",
"summary": "校验 xpcall 在调用栈展开前调用错误处理函数,完整保留调用栈供 traceback 诊断",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_syntax_vs_runtime_errors(),
case_assert_and_error_levels(),
case_pcall_protected_call(),
case_xpcall_handler_before_unwind(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`pcall` 返回错误信息时调用栈已经销毁,只能看到最内层报错点;而 `xpcall` 会在栈展开前触发错误处理函数,因此 `debug.traceback` 能完整打印从入口到出错点的整条调用链。