蓝色天空.知识 · 实践 · 创造
我的收藏
Lua 教程目录 23章
Lua / LEARN BY DOING

Lua 数据类型

全面解析 Lua 动态类型系统与 8 种基本数据类型(nil、boolean、number、string、function、userdata、thread、table)的语义、真值规则与常见陷阱。

学完这一章,你能够

  • 全面解析 Lua 动态类型系统与 8 种基本数据类型(nil、boolean、number、string、function、userdata、thread、table)的语义、真值规则与常见陷阱。

动态类型与 8 种基本数据类型

Lua 是动态类型语言,变量本身没有固定类型,类型附着于值上;任何值都可存入变量、作为参数传递或作为函数结果返回。Lua 共有 8 种基本类型:`nil`、`boolean`、`number`、`string`、`userdata`、`function`、`thread` 和 `table`(见下表)。内置函数 `type(v)` 会以字符串形式返回任意值的类型名称,因此 `type(type(X))` 恒为 `"string"`。

nil(空)与 boolean(布尔)真值规则

`nil` 类型仅有唯一值 `nil`,代表“无有效值”,未赋值的变量默认求值为 `nil`。对全局变量或 `table` 中的字段赋 `nil` 等同于将其删除。判断类型是否为 `nil` 时要格外小心:`type(X)` 返回的是字符串 `"nil"` 而不是 `nil` 值本身,因此 `type(X) == nil` 恒为 `false`,正确写法是 `type(X) == "nil"`(或直接写 `X == nil`)。

`boolean` 类型包含 `true` 和 `false`。与 C/Python/JavaScript 不同,Lua 在条件判断中**只把 `false` 和 `nil` 视为假,其余所有值一律为真**——数字 `0`、空字符串 `""` 和空表 `{}` 在 Lua 中都是真值。

number(数字)与 string(字符串)

`number` 表示数值类型。早期 Lua 5.1/5.2 默认仅用双精度浮点数(double)表示所有数字;自 Lua 5.3/5.4 起,`number` 在内部细分为 64 位整数(integer)和 64 位双精度浮点(float)两种子类型(可通过 `math.type()` 区分,亦可在 `luaconf.h` 定制位宽),但 `type()` 对 `2`、`2.2`、`0.2`、`2e+1`、`7.8263692594256e-06` 均统一返回 `"number"`。

字符串可用单引号、双引号或长括号 `[[ ... ]]`(多行原样文本块)表示。当对数字格式字符串执行算术运算(如 `"2" + 6`、`"-2e2" * "6"`)时,Lua 会尝试隐式转换为数字;若无法转换(如 `"error" + 1`)则抛出运行时算术错误。字符串拼接必须使用 `..` 运算符(对数字操作数也会转成字符串拼接,如 `157 .. 428` 得 `"157428"`),而前缀 `#` 运算符用于计算字符串的字节长度(如 `#"www.mbsky.com"` 为 13)。

table、function、thread 与 userdata

`table` 通过构造表达式 `{}` 创建,既是关联数组也是列表:键可以是数字、字符串或任意非 `nil` 值;列表形式的表默认从索引 `1` 开始而非 `0`;表的容量动态增长,访问未初始化的键会返回 `nil`。

函数(`function`)在 Lua 中是第一类值(First-Class Value),既可以赋值给其他变量(如 `factorial2 = factorial1`),也可以直接以匿名函数字面量的形式作为回调函数传给高阶函数遍历处理表数据。

`thread` 代表独立的执行线程,在 Lua 中主要体现为协同程序(coroutine):每个协程拥有独立调用栈、局部变量与指令指针,同时共享全局变量;与操作系统多线程可并行执行不同,同一时刻仅有一个协程处于运行态,且只有主动挂起(yield)才会交出控制权。`userdata` 则用于承载宿主 C/C++ 程序创建的自定义数据结构或指针,供 Lua 脚本安全引用与操作。

Lua 8 种基本数据类型一览

数据类型核心语义说明
nil仅包含唯一值 nil,表示无有效值;条件判断中为假,赋值给变量或表键可用于删除。
boolean包含 true 和 false 两个布尔值;Lua 中仅 false 与 nil 为假,0 和空串均为真。
number数值类型,涵盖整数与双精度浮点数(Lua 5.3+ 内部区分 integer/float 子类型)。
string不可变字节序列,由单引号、双引号或 [[...]] 长括号界定。
function由 Lua 或 C 编写的一等函数值,可赋值、传参、返回并构成闭包。
userdata宿主 C/C++ 分配的自定义内存块或指针封装,供 Lua 与原生数据结构交互。
thread独立执行控制流,用于实现非抢占式协同程序(coroutine)。
table通用动态关联数组,以 {} 构造,支持任意非 nil 键,默认列表索引从 1 起始。

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

含完整源码 · 188 行
展开查看收起
python
"""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()
离线脚本验证 8 种类型标识与 type(X)=="nil"、0 与空串为真、数字串算术转换与非法串报错、table 1-based 索引及匿名函数回调。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2510.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Lua

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

下载课程关联工程包:Lua

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

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

因为 `type()` 的返回值永远是字符串,当 `x` 为 `nil` 时 `type(x)` 返回字符串 `"nil"`,字符串与 `nil` 值类型不同故比较为 `false`;应写作 `type(x) == "nil"` 或 `x == nil`。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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