"""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()
本例需在 Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。
入口文件:projects/lua-error-handling-lab/explore-error-handling.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-error-handling.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联23章) · 含当前章节或实例 · mbskycom202612a2510.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2519.zip