Lua 数据结构深度解析
Lua 的设计哲学是“唯一的复合数据结构”:
- 表 (Table):兼具数组(Array Part)与哈希字典(Hash Part)双重底层表示。
- 极低内存开销:通过 1-based 连续整数键激活高速数组部分,提供与原生 C 数组媲美的访问速度。
📊 核心结构与操作
| 结构 | Lua 表达 | 典型复杂度 | 特征 |
|---|---|---|---|
| 数组 | 连续数字索引 Table | 索引 $O(1)$,table.insert/remove 尾部 $O(1)$ | 紧凑 C 数组底层 |
| 字典 | 字符串/对象键 Table | 增删查 $O(1)$ | 开放寻址哈希表 |
1. 线性结构:Lua Table 动态数组
lua
print("=== Lua Table as Dynamic Array ===")
local arr = {10, 20}
table.insert(arr, 30)
assert(#arr == 3, "Length assertion failed")
assert(arr[2] == 20, "Index assertion failed")
local popped = table.remove(arr)
assert(popped == 30, "Remove assertion failed")
print(string.format("Lua Table len=%d, elements=[%d, %d]", #arr, arr[1], arr[2]))
print("Lua Dynamic Array tests passed successfully.")🐳 Docker Verified📋
hello-lang-lua:5.5.1Exit Code: 0
=== Lua dynamic_array ===
Lua DSA tests passed successfully.