Skip to content

05 - 表(table)与迭代

Lua 唯一的复合类型,同时充当数组和哈希表。

一、创建

1. 字面量

-- 空表
local empty = {}

-- 数组(连续整数下标 1, 2, 3, ...)
local arr = {10, 20, 30, 40}

-- 哈希表(字符串键)
local person = {
    name = "alice",
    age = 30,
    city = "Beijing",
}

-- 混合
local mixed = {
    100, 200, 300,                  -- [1]=100, [2]=200
    name = "test",                    -- ["name"]="test"
    [10] = 500,                       -- [10]=500
    ["key with space"] = "value",     -- 显式字符串键
}

-- 嵌套
local config = {
    server = {host = "0.0.0.0", port = 8080},
    database = {url = "postgres://..."},
}

2. 构造函数

-- table.create(5, 0)    -- Lua 5.4 新增

-- 旧方法(兼容性)
local t = {}
for i = 1, 10 do t[i] = 0 end

二、访问

local p = {name = "alice", age = 30}

-- 点语法(字段名是合法标识符)
print(p.name)        -- "alice"
p.age = 31

-- 索引语法(任意键)
print(p["name"])      -- "alice"
local key = "name"
print(p[key])         -- "alice"

-- 不存在的字段返回 nil
print(p.email)        -- nil

-- 多级访问
print(config.server.host)   -- "0.0.0.0"

三、修改

local t = {a = 1}
t.b = 2                            -- 添加字段
t["c"] = 3                          -- 任意键
t.a = nil                            -- 删除字段

四、长度运算符 #

local arr = {10, 20, 30}
print(#arr)            -- 3

-- 数组的"边界"取决于非 nil 元素的位置
local sparse = {1, 2, nil, 4, 5}
print(#sparse)         -- 5(Lua 数组长度的不确定行为)

-- 哈希表:无定义顺序,# 可能是 0
local h = {a = 1, b = 2}
print(#h)              -- 0 或 2(未定义)

五、遍历

1. pairs - 通用遍历

local t = {a = 1, b = 2, c = 3}

for k, v in pairs(t) do
    print(k, v)
end
-- 遍历所有 key-value,跳过 nil 值,顺序**不固定**

2. ipairs - 数组遍历

local arr = {10, 20, 30}

for i, v in ipairs(arr) do
    print(i, v)
end
-- 1 10
-- 2 20
-- 3 30

-- 遇 nil 停止(不遍历到末尾)
local sparse = {10, 20, nil, 40}
for i, v in ipairs(sparse) do
    print(i, v)
end
-- 只遍历 1 10, 2 20(遇 nil 停止)

3. 自定义迭代器

-- 迭代器函数返回 nil 即终止
local function range(from, to, step)
    step = step or 1
    local current = from - step
    return function()
        current = current + step
        if current > to then return nil end
        return current
    end
end

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

-- 泛型 for 的循环变量可以是多个
local function pairsByKeys(t)
    local keys = {}
    for k in pairs(t) do table.insert(keys, k) end
    table.sort(keys)
    local i = 0
    return function()
        i = i + 1
        local k = keys[i]
        if k then return k, t[k] end
    end
end

local h = {c = 3, a = 1, b = 2}
for k, v in pairsByKeys(h) do
    print(k, v)
end
-- a 1
-- b 2
-- c 3

六、table 标准库

local t = {1, 2, 3, 4, 5}

-- insert(末尾追加,默认位置)
table.insert(t, 6)               -- {1,2,3,4,5,6}
table.insert(t, 1, 99)           -- 在位置 1 插入:{99,1,2,3,4,5,6}

-- remove(默认末尾)
table.remove(t)                   -- 移除末尾,返回 6
table.remove(t, 1)                -- 移除位置 1,返回 99

-- concat(连接元素为字符串)
print(table.concat({1, 2, 3}, "-"))   -- "1-2-3"
print(table.concat({"a", "b"}, ""))  -- "ab"

-- sort(默认升序)
local nums = {3, 1, 4, 1, 5}
table.sort(nums)
-- {1, 1, 3, 4, 5}

-- 自定义排序
table.sort(nums, function(a, b) return a > b end)

-- unpack(解包为多值)
local arr = {10, 20, 30}
print(table.unpack(arr))          -- 10  20  30
local a, b, c = table.unpack(arr)

-- move(移动元素,Lua 5.3+)
local a = {1, 2, 3}
table.move(a, 1, 3, 1, b)
-- 把 a[1..3] 移到 b[1..3],b 自动扩展

七、综合实战:用户管理

-- user_mgr.lua
local M = {}

local users = {}  -- 存储:{id = {name=, age=}}

local next_id = 1

function M.create(name, age)
    local user = {id = next_id, name = name, age = age}
    users[next_id] = user
    next_id = next_id + 1
    return user
end

function M.find(id)
    return users[id]  -- 不存在返回 nil
end

function M.update(id, name, age)
    local u = users[id]
    if u then
        u.name = name or u.name
        u.age = age or u.age
    end
    return u
end

function M.delete(id)
    users[id] = nil
end

function M.list()
    local out = {}
    for _, u in pairs(users) do
        table.insert(out, u)
    end
    -- 按 id 排序
    table.sort(out, function(a, b) return a.id < b.id end)
    return out
end

function M.count()
    -- 计数:遍历非 nil 键
    local n = 0
    for _ in pairs(users) do n = n + 1 end
    return n
end

return M
-- test.lua
local UserMgr = require("user_mgr")

local u1 = UserMgr.create("alice", 30)
local u2 = UserMgr.create("bob", 25)
print(UserMgr.count())    -- 2

UserMgr.update(1, "Alice", 31)

for _, u in ipairs(UserMgr.list()) do
    print(u.id, u.name, u.age)
end
-- 1  Alice  31
-- 2  bob    25

八、要点速记

  • {} 创建表,既是数组也是哈希表
  • 下标默认从 1 开始(Lua 习惯)
  • # 只能用于"序列"(1..n 形式)
  • pairs 遍历所有 key-value(无序),ipairs 数组遍历(遇 nil 停)
  • table.insert / remove / concat / sort / unpack / move
  • table 是引用类型,赋值/传参是引用传递
  • 删除字段:t.key = nil
  • unpack 解包为多返回值
  • 遍历顺序不固定,需要稳定顺序先 sort key