"""Offline Lua 5.4 semantic verification lab for Chapter 18 (file-io)."""
import json
import re
import tempfile
from pathlib import Path
VERSION = "CPython 3.12.14 offline Lua 5.4 semantic verifier (lua interpreter absent)"
def case_open_modes_and_simple_io_workflow():
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "test.lua"
target.write_text("-- test.lua 文件\nprint('ok')\n", encoding="utf-8")
# Simple mode: open r -> read first line -> close
with target.open("r", encoding="utf-8") as fh:
first_line = fh.readline().rstrip("\r\n")
# Simple mode: open a -> append comment -> close
with target.open("a", encoding="utf-8") as fh:
fh.write("-- test.lua 文件末尾注释")
lines = target.read_text(encoding="utf-8").splitlines()
expected = {
"first_line": "-- test.lua 文件",
"line_count_after_append": 3,
"last_line": "-- test.lua 文件末尾注释",
}
actual = {
"first_line": first_line,
"line_count_after_append": len(lines),
"last_line": lines[-1],
}
return {
"name": "open_modes_and_simple_io_workflow",
"summary": "在临时目录模拟简单模式 r 读取首行与 a 追加末尾注释,确认原有内容保留",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_read_formats_n_a_l_and_count():
with tempfile.TemporaryDirectory() as tmp:
p = Path(tmp) / "data.txt"
p.write_text("42.5 hello\nsecond line\n12345rest", encoding="utf-8")
raw = p.read_text(encoding="utf-8")
# "*n" reads numeric prefix
m_num = re.match(r"\s*([+-]?\d+(?:\.\d+)?)", raw)
read_n = float(m_num.group(1)) if m_num else None
rem = raw[m_num.end() :] if m_num else raw
# "*l" reads rest of current line without newline
first_nl = rem.find("\n")
read_l1 = rem[:first_nl]
rem2 = rem[first_nl + 1 :]
second_nl = rem2.find("\n")
read_l2 = rem2[:second_nl]
rem3 = rem2[second_nl + 1 :]
# number (5) reads 5 characters; "*a" reads remaining content
read_5 = rem3[:5]
read_a = rem3[5:]
expected = {
"read_n": 42.5,
"read_l1": " hello",
"read_l2": "second line",
"read_5": "12345",
"read_a": "rest",
}
actual = {
"read_n": read_n,
"read_l1": read_l1,
"read_l2": read_l2,
"read_5": read_5,
"read_a": read_a,
}
return {
"name": "read_formats_n_a_l_and_count",
"summary": "校验 io.read / file:read 的 *n、*l、指定字节数与 *a 四种读取格式",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_complete_mode_seek_and_flush():
with tempfile.TemporaryDirectory() as tmp:
p = Path(tmp) / "seek_test.lua"
payload = b"-- test.lua header\n-- tail_marker--test"
p.write_bytes(payload)
with p.open("rb") as fh:
fh.seek(0, 2) # file:seek("end", 0) -> file size
total_size = fh.tell()
fh.seek(-19, 2) # file:seek("end", -19)
tail = fh.read().decode("utf-8")
fh.seek(0, 0) # file:seek("set", 0)
pos_start = fh.tell()
expected = {
"total_size": len(payload),
"tail_slice": "-- tail_marker--test"[1:],
"pos_after_set": 0,
}
actual = {"total_size": total_size, "tail_slice": tail, "pos_after_set": pos_start}
return {
"name": "complete_mode_seek_and_flush",
"summary": "校验完全模式下 file:seek(\"end\", -offset) 逆向定位读取尾部及 set/cur/end 基准",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_tmpfile_io_type_and_lines_iterator():
with tempfile.TemporaryDirectory() as tmp:
p = Path(tmp) / "main.lua"
p.write_text("line1\nline2\nline3\n", encoding="utf-8")
iterated = [ln.rstrip("\r\n") for ln in p.open("r", encoding="utf-8")]
tf = tempfile.TemporaryFile(mode="w+", encoding="utf-8")
open_type = "file" if not tf.closed else "closed file"
tf.write("temp-data")
tf.flush()
tf.seek(0)
temp_val = tf.read()
tf.close()
closed_type = "closed file" if tf.closed else "file"
non_file_type = None
expected = {
"lines_iterated": ["line1", "line2", "line3"],
"temp_val": "temp-data",
"io_type_states": ["file", "closed file", None],
}
actual = {
"lines_iterated": iterated,
"temp_val": temp_val,
"io_type_states": [open_type, closed_type, non_file_type],
}
return {
"name": "tmpfile_io_type_and_lines_iterator",
"summary": "校验 io.tmpfile 自动清理临时句柄、io.type 三态(file/closed file/nil)及 io.lines 逐行迭代",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_open_modes_and_simple_io_workflow(),
case_read_formats_n_a_l_and_count(),
case_complete_mode_seek_and_flush(),
case_tmpfile_io_type_and_lines_iterator(),
]
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-file-io-lab/explore-file-io.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-file-io.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联23章) · 含当前章节或实例 · mbskycom202612a2510.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2520.zip