Lua 教程
概述 Lua 轻量级嵌入式脚本语言的起源、设计目标、核心语言特性、主流工程应用场景及首个 Hello World 脚本示例。
学完这一章,你能够
- 概述 Lua 轻量级嵌入式脚本语言的起源、设计目标、核心语言特性、主流工程应用场景及首个 Hello World 脚本示例。
Lua 起源与嵌入式设计目标
Lua 是一门轻量、高效且以标准 ISO C 编写的开源脚本语言,由巴西里约热内卢天主教大学(PUC-Rio)的 Roberto Ierusalimschy、Waldemar Celes 与 Luiz Henrique de Figueiredo 三人团队于 1993 年创立。它从诞生之初就面向“嵌入式扩展”定位,旨在无缝集成到 C/C++ 等宿主应用中,为宿主提供灵活的脚本配置与二次定制能力。
核心语言特性与典型应用场景
Lua 编译后的核心运行时仅百余 KB,内存占用极低,并借助简洁的 C API 实现与宿主语言的双向互操作。语言本身兼具面向过程与函数式编程能力:具备自动垃圾回收机制;仅提供 `table` 这一种通用复合数据结构即可统一表达数组、哈希表、集合与对象;内置轻量级模式匹配、一等函数、词法闭包以及非抢占式协同程序(coroutine,并非操作系统内核线程),结合闭包与元表还能灵活搭建数据抽象、继承与多态等面向对象机制。
凭借体量小巧与嵌入便捷的优势,Lua 广泛应用于游戏逻辑与热更新脚本、独立桌面/工具应用扩展、Web 服务器脚本(如 OpenResty/Nginx)、数据库插件与代理(如 MySQL Proxy、MySQL Workbench)以及入侵检测等安全系统规则引擎。
第一个 Lua 程序
Lua 源码文件通常以 `.lua` 为扩展名。最简入口无需主函数包裹或行尾分号,直接编写 `print("Hello World!")` 即可。需要注意的是,当传入字面量 `"Hello World!"` 时,终端实际精确输出 `Hello World!`(不额外添加逗号,且首字母大写保持原样)。
离线校验本机 Lua 工具链状态、首个 Hello World 输出与核心特性模型
"""Offline Lua 5.4 semantic verification lab for Chapter 01 (tutorial)."""
import json
import re
import shutil
VERSION = "CPython 3.12.14 offline Lua 5.4 semantic verifier (lua interpreter absent)"
def case_toolchain_absence_probe():
bins = {k: shutil.which(k) for k in ("lua", "lua5.4", "luac", "luajit", "luarocks")}
expected = {
"lua_found": False,
"luac_found": False,
"luarocks_found": False,
"offline_mode": True,
}
actual = {
"lua_found": bins["lua"] is not None or bins["lua5.4"] is not None,
"luac_found": bins["luac"] is not None,
"luarocks_found": bins["luarocks"] is not None,
"offline_mode": all(v is None for v in bins.values()),
}
return {
"name": "toolchain_absence_probe",
"summary": "如实探测本机 lua/luac/luarocks 可执行文件,确认当前处于离线语义验证环境",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_hello_world_print_semantics():
src = 'print("Hello World!")\n'
m = re.match(r'^print\("([^"]*)"\)\s*$', src.strip())
output = (m.group(1) + "\n") if m else ""
expected = {
"extension": ".lua",
"call_target": "print",
"stdout": "Hello World!\n",
}
actual = {
"extension": ".lua",
"call_target": "print" if m else "",
"stdout": output,
}
return {
"name": "hello_world_print_semantics",
"summary": "校验首个 .lua 脚本中 print(\"Hello World!\") 的调用语法与精确标准输出",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_lua_core_feature_model():
paradigms = ["procedural", "functional", "data-driven", "prototype-oop"]
universal_ds = {"array": "table", "hash_map": "table", "set": "table", "object": "table"}
expected = {
"origin_year": 1993,
"implementation_lang": "ISO C",
"single_compound_type": "table",
"paradigm_count": 4,
}
actual = {
"origin_year": 1993,
"implementation_lang": "ISO C",
"single_compound_type": next(iter(set(universal_ds.values()))),
"paradigm_count": len(paradigms),
}
return {
"name": "lua_core_feature_model",
"summary": "核对 Lua 起源年份、标准 C 实现、table 统一数据结构与多范式特性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_lua_application_domains():
domains = [
"game-scripting",
"embedded-app-extension",
"web-nginx-openresty",
"database-plugin",
"security-ids",
]
expected = {"domain_count": 5, "supports_c_host_embedding": True}
actual = {"domain_count": len(domains), "supports_c_host_embedding": "embedded-app-extension" in domains}
return {
"name": "lua_application_domains",
"summary": "校验 Lua 在游戏、嵌入式扩展、Web、数据库插件及安全系统中的典型定位",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_toolchain_absence_probe(),
case_hello_world_print_semantics(),
case_lua_core_feature_model(),
case_lua_application_domains(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 离线脚本如实探测本机未安装 lua/luac/luarocks,验证 print("Hello World!") 输出格式以及 Lua 起源、table 通用结构与五大应用领域。
所需环境:Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。
当前源码 SHA256:fea6ba9013729a866c06ad7d7df69c237fbfa0cf2e241c9ac016dac3c2d202a5
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。
ZIP SHA256:32fb47c1300aa1648f04e32fb22be161e5c213603b48ac424898f216831630b8
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么说 Lua 仅凭一种复合类型 `table` 就能覆盖数组、字典与对象?
展开参考解答
`table` 是动态关联数组,既支持从 1 开始的连续整数键充当数组,也支持任意非 nil 键充当哈希映射,配合函数值和元表(metatable)还能模拟类、继承与方法派发。