2Programming in Lua(第4版)

数据结构

表的力量

table数组字典迭代器

🎯 AI 时代的学习建议:不要只读理论。理解这一章的设计动机(为什么需要这个概念?)和边界条件(什么情况下会失效?)。当 AI 生成的代码涉及这些概念时,你能判断它是否用对了场景。AI 能帮你总结内容,但无法替代你亲手阅读、思考、建立直觉的过程。

第2章:数据结构

一、导读

1.1 本章学习目标

第2章讲解 Lua 的唯一数据结构——table:数组、字典、迭代器。

本章核心学习目标:

  • 掌握 table 的多重角色:数组、字典、对象、模块
  • 理解 table 的数组和字典用法
  • 掌握 table 操作函数
  • 理解 ipairs 和 pairs 的区别

1.2 为什么本章如此重要

table 是 Lua 中最重要也最灵活的数据结构。理解 table 是掌握 Lua 的关键。

1.3 核心问题引导

table 如何同时作为数组和字典使用?

ipairs 和 pairs 有什么区别?

table 的 # 操作符在什么情况下不可靠?


二、核心概念详解

2.1 table 基础

lua
-- 创建 table
local t = {}

-- 作为数组 (索引从 1 开始!)
local arr = {"apple", "banana", "cherry"}
print(arr[1])  -- apple (Lua 数组从 1 开始)
print(arr[2])  -- banana
print(#arr)    -- 3

-- 作为字典
local person = {
    name = "Alice",
    age = 30,
    city = "NYC"
}
print(person.name)   -- Alice
print(person["age"]) -- 30

-- 混合使用
local mixed = {1, 2, 3, name = "Bob", age = 25}
print(mixed[1])      -- 1
print(mixed.name)    -- Bob

2.2 table 操作

lua
-- table.insert
local t = {1, 2, 3}
table.insert(t, 4)        -- 末尾插入: {1, 2, 3, 4}
table.insert(t, 2, 10)    -- 在位置 2 插入: {1, 10, 2, 3, 4}

-- table.remove
table.remove(t)           -- 移除最后一个: {1, 10, 2, 3}
table.remove(t, 2)        -- 移除位置 2: {1, 2, 3}

-- table.sort
local nums = {3, 1, 4, 1, 5, 9}
table.sort(nums)          -- {1, 1, 3, 4, 5, 9}
table.sort(nums, function(a, b) return a > b end)  -- 降序

-- table.concat
local words = {"hello", "world"}
print(table.concat(words, " "))  -- hello world

-- table.move (Lua 5.3+)
local src = {1, 2, 3, 4, 5}
local dst = {}
table.move(src, 1, 3, 1, dst)  -- dst = {1, 2, 3}

2.3 迭代

lua
-- ipairs: 遍历数组部分 (从 1 开始,遇到 nil 停止)
local arr = {"a", "b", "c"}
for i, v in ipairs(arr) do
    print(i, v)
end

-- pairs: 遍历所有键值对 (无序)
local dict = {a = 1, b = 2, c = 3}
for k, v in pairs(dict) do
    print(k, v)
end

-- 自定义迭代器
function range(from, to)
    local i = from - 1
    return function()
        i = i + 1
        if i > to then return nil end
        return i
    end
end

for i in range(1, 5) do
    print(i)  -- 1, 2, 3, 4, 5
end

三、实战案例

3.1 案例一:实现一个简单的数据库

lua
-- 用 table 实现简单的键值数据库
local DB = {}

function DB.set(key, value)
    DB[key] = value
end

function DB.get(key)
    return DB[key]
end

function DB.delete(key)
    DB[key] = nil
end

function DB.keys()
    local result = {}
    for k in pairs(DB) do
        result[#result + 1] = k
    end
    return result
end

-- 使用
DB.set("name", "Alice")
DB.set("age", 30)
DB.set("city", "NYC")

print(DB.get("name"))  -- Alice
print("Keys:", table.concat(DB.keys(), ", "))

DB.delete("age")
print("Keys after delete:", table.concat(DB.keys(), ", "))

四、本章小结

table 是 Lua 唯一的数据结构,可以做数组、字典、对象

Lua 数组从 1 开始索引

ipairs 遍历数组部分,pairs 遍历所有键值对


五、思考与练习

为什么 Lua 数组从 1 开始而不是 0?

如何实现一个有序的字典?


2/8数据结构
0%