蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 Lua 8 种基本类型、真值边界、字符串算术转换与一等函数回调

PYTHONWindows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。explore-data-types.py
explore-data-types.py188 行
"""Offline Lua 5.4 semantic verification lab for Chapter 05 (data-types)."""
import json

VERSION = "CPython 3.12.14 offline Lua 5.4 semantic verifier (lua interpreter absent)"


def lua_type(val) -> str:
    if val is None:
        return "nil"
    if isinstance(val, bool):
        return "boolean"
    if isinstance(val, (int, float)):
        return "number"
    if isinstance(val, str):
        return "string"
    if callable(val):
        return "function"
    if isinstance(val, dict):
        return "table"
    if isinstance(val, tuple) and len(val) == 2 and val[0] in ("thread", "userdata"):
        return val[0]
    raise TypeError(f"unsupported value: {val!r}")


def lua_truthy(val) -> bool:
    return not (val is None or val is False)


def lua_add(a, b):
    def to_num(x):
        if isinstance(x, (int, float)) and not isinstance(x, bool):
            return float(x)
        if isinstance(x, str):
            return float(x)
        raise ValueError("attempt to perform arithmetic on a non-number value")

    return to_num(a) + to_num(b)


def case_eight_types_and_nil_deletion():
    samples = {
        "nil": None,
        "boolean": True,
        "number": 10.4 * 3,
        "string": "Hello world",
        "function": print,
        "userdata": ("userdata", "C_struct_ptr"),
        "thread": ("thread", "coro_1"),
        "table": {"key1": "val1", "key2": "val2", 1: "val3"},
    }
    observed = {k: lua_type(v) for k, v in samples.items()}
    tab = dict(samples["table"])
    tab.pop("key1", None)  # tab.key1 = nil deletes key1
    type_of_nil = lua_type(None)
    expected = {
        "all_8_types_match": True,
        "type_x_eq_nil": False,
        "type_x_eq_str_nil": True,
        "type_of_type_x": "string",
        "remaining_keys": ["key2", "1"],
    }
    actual = {
        "all_8_types_match": all(k == v for k, v in observed.items()),
        "type_x_eq_nil": (type_of_nil is None),
        "type_x_eq_str_nil": (type_of_nil == "nil"),
        "type_of_type_x": lua_type(type_of_nil),
        "remaining_keys": [str(k) for k in tab.keys()],
    }
    return {
        "name": "eight_types_and_nil_deletion",
        "summary": "校验 Lua 8 种基本数据类型、type() 恒返回字符串及 nil 赋值删除 table 键的行为",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_boolean_truthiness_and_numbers():
    truth_table = {
        "false": lua_truthy(False),
        "nil": lua_truthy(None),
        "zero": lua_truthy(0),
        "empty_str": lua_truthy(""),
        "empty_table": lua_truthy({}),
        "true": lua_truthy(True),
    }
    nums = [2, 2.2, 0.2, 2e1, 0.2e-1, 7.8263692594256e-06]
    expected = {
        "only_false_and_nil_falsy": True,
        "zero_is_truthy": True,
        "empty_str_is_truthy": True,
        "all_numbers_typed_number": True,
    }
    actual = {
        "only_false_and_nil_falsy": (not truth_table["false"]) and (not truth_table["nil"]),
        "zero_is_truthy": truth_table["zero"],
        "empty_str_is_truthy": truth_table["empty_str"],
        "all_numbers_typed_number": all(lua_type(n) == "number" for n in nums),
    }
    return {
        "name": "boolean_truthiness_and_numbers",
        "summary": "校验仅 false 与 nil 为假(0 与空串为真)以及整数/小数/科学计数法均属 number 类型",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_string_coercion_concat_and_len():
    coerced_sum = lua_add("2", 6)
    coerced_mul = float("-2e2") * float("6")
    err_caught = False
    try:
        lua_add("error", 1)
    except ValueError:
        err_caught = True
    concat_num = f"{157}{428}"
    domain = "www.mbsky.com"
    expected = {
        "str_plus_num": 8.0,
        "sci_mul": -1200.0,
        "invalid_str_arith_raises": True,
        "concat_nums": "157428",
        "hash_len": 13,
    }
    actual = {
        "str_plus_num": coerced_sum,
        "sci_mul": coerced_mul,
        "invalid_str_arith_raises": err_caught,
        "concat_nums": concat_num,
        "hash_len": len(domain.encode("utf-8")),
    }
    return {
        "name": "string_coercion_concat_and_len",
        "summary": "校验数字字符串算术自动转换、非法字符串算术报错、.. 拼接与 # 字节长度",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_table_indexing_and_first_class_functions():
    a = {"key": "value", 10: 22}
    a[10] = a[10] + 11
    fruits = {1: "apple", 2: "pear", 3: "orange", 4: "grape"}

    def fact(n):
        return 1 if n == 0 else n * fact(n - 1)

    fact_alias = fact
    tab = {"key1": "val1", "key2": "val2"}
    mapped = [fn(k, v) for k, v in tab.items() for fn in [lambda key, val: f"{key}={val}"]]
    expected = {
        "assoc_num_val": 33,
        "missing_key": None,
        "one_based_keys": [1, 2, 3, 4],
        "fact5_via_alias": 120,
        "anon_callback_output": ["key1=val1", "key2=val2"],
    }
    actual = {
        "assoc_num_val": a[10],
        "missing_key": a.get("none", None),
        "one_based_keys": list(fruits.keys()),
        "fact5_via_alias": fact_alias(5),
        "anon_callback_output": mapped,
    }
    return {
        "name": "table_indexing_and_first_class_functions",
        "summary": "校验 table 1-based 索引/动态扩容/缺省 nil,以及函数作为第一类值与匿名回调传递",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_eight_types_and_nil_deletion(),
        case_boolean_truthiness_and_numbers(),
        case_string_coercion_concat_and_len(),
        case_table_indexing_and_first_class_functions(),
    ]
    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-data-types-lab/explore-data-types.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-data-types.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Lua

课程关联工程包(登记关联23章) · 含当前章节或实例 · mbskycom202612a2510.zip

下载课程关联工程包:Lua

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2513.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习