"""Offline Lua 5.4 semantic verification lab for Chapter 04 (basic-syntax)."""
import json
import re
VERSION = "CPython 3.12.14 offline Lua 5.4 semantic verifier (lua interpreter absent)"
LUA_KEYWORDS = (
"and", "break", "do", "else",
"elseif", "end", "false", "for",
"function", "if", "in", "local",
"nil", "not", "or", "repeat",
"return", "then", "true", "until",
"while", "goto",
)
def is_valid_lua_ident(name: str) -> bool:
if name in LUA_KEYWORDS:
return False
return bool(re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", name))
def strip_lua_comments(src: str) -> str:
# Remove --[[ ... ]] (non-nested) first, then -- to end of line
no_block = re.sub(r"--\[\[.*?\]\]", "", src, flags=re.DOTALL)
no_line = re.sub(r"--[^\n]*", "", no_block)
return "\n".join(ln for ln in no_line.splitlines() if ln.strip())
def case_interactive_script_and_shebang():
script = '#!/usr/local/bin/lua\nprint("Hello World!")\nprint("www.mbsky.com")\n'
lines = script.splitlines()
shebang_ignored = lines[0].startswith("#")
body = [ln for ln in lines[1:] if ln.strip()]
expected = {"shebang_ignored": True, "statement_count": 2, "extension": ".lua"}
actual = {"shebang_ignored": shebang_ignored, "statement_count": len(body), "extension": ".lua"}
return {
"name": "interactive_script_and_shebang",
"summary": "校验脚本首行 #! 解释器标记忽略规则及交互式/脚本式执行输出结构",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_comment_rules_and_non_nesting():
valid_src = "-- 单行注释\n--[[\n多行注释\n--]]\nlocal x = 1\n"
nested_src = "--[[\n外层\n--[[\n内层\n]]\n]]"
cleaned_valid = strip_lua_comments(valid_src)
cleaned_nested = strip_lua_comments(nested_src)
expected = {"valid_code_left": "local x = 1", "nested_leaves_dangling_close": "]]"}
actual = {"valid_code_left": cleaned_valid, "nested_leaves_dangling_close": cleaned_nested}
return {
"name": "comment_rules_and_non_nesting",
"summary": "校验 -- 单行注释、--[[...]] 多行注释及同名长括号不可直接嵌套导致多余 ]] 报错的词法现象",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_identifiers_and_keywords():
valid_samples = ["mohd", "zara", "abc", "move_name", "a_123", "myname50", "_temp", "j", "a23b9", "retVal"]
invalid_samples = ["123abc", "user@host", "$price", "rate%1", "function", "goto"]
case_distinct = ("BlueSky" != "bluesky")
reserved_internal = bool(re.match(r"^_[A-Z]+$", "_VERSION"))
expected = {
"keyword_count": 22,
"all_valid_accepted": True,
"all_invalid_rejected": True,
"case_sensitive": True,
"internal_convention_match": True,
}
actual = {
"keyword_count": len(LUA_KEYWORDS),
"all_valid_accepted": all(is_valid_lua_ident(s) for s in valid_samples),
"all_invalid_rejected": all(not is_valid_lua_ident(s) for s in invalid_samples),
"case_sensitive": case_distinct,
"internal_convention_match": reserved_internal,
}
return {
"name": "identifiers_and_keywords",
"summary": "校验 22 个 Lua 保留关键字、合法/非法标识符规则、大小写敏感及 _VERSION 内部命名约定",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_global_variable_lifecycle():
env = {}
before = env.get("b", None)
env["b"] = 10
assigned = env.get("b", None)
env.pop("b", None) # b = nil deletes the global key
after_nil = env.get("b", None)
expected = {"before": None, "assigned": 10, "after_nil": None, "exists_after_nil": False}
actual = {"before": before, "assigned": assigned, "after_nil": after_nil, "exists_after_nil": "b" in env}
return {
"name": "global_variable_lifecycle",
"summary": "模拟未初始化全局变量返回 nil、赋值创建以及赋 nil 删除全局变量的语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_interactive_script_and_shebang(),
case_comment_rules_and_non_nesting(),
case_identifiers_and_keywords(),
case_global_variable_lifecycle(),
]
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-basic-syntax-lab/explore-basic-syntax.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-basic-syntax.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2511.zip
课程关联工程包(登记关联23章) · 含当前章节或实例 · mbskycom202612a2510.zip