
在 Lua 编程语言中,表(table)是一种非常强大且灵活的数据结构。它可以被看作是关联数组,也就是以键值对的方式来存储数据。这种特性使得表在 Lua 中应用广泛,无论是简单的数据存储,还是复杂的数据管理和算法实现,表都能发挥重要作用。本文将深入探讨 Lua 表作为关联数组的特性、使用方法以及一些实用的例子。
在 Lua 中,表是一种动态的数据结构,它可以存储任意类型的值,包括数字、字符串、函数甚至其他表。表的键可以是除了 nil 以外的任何类型,值可以是任意类型。表的创建非常简单,使用大括号 {} 即可。
-- 创建一个空表local myTable = {}-- 向表中添加键值对myTable["name"] = "John"myTable["age"] = 30myTable[1] = "apple"-- 访问表中的值print(myTable["name"]) -- 输出: Johnprint(myTable["age"]) -- 输出: 30print(myTable[1]) -- 输出: apple
除了逐个添加键值对,还可以在创建表时直接初始化。
-- 直接初始化表local student = {name = "Alice",age = 20,grades = {math = 90, english = 85}}-- 访问表中的值print(student.name) -- 输出: Aliceprint(student.grades.math) -- 输出: 90
可以使用方括号 [] 或点号 . 来访问表中的值。使用方括号时,键可以是变量或表达式;使用点号时,键必须是合法的标识符。
local key = "name"print(student[key]) -- 输出: Alice
Lua 提供了两种主要的方式来遍历表:pairs 和 ipairs。
pairs 遍历pairs 可以遍历表中的所有键值对,包括非连续的键。
local fruit = {["apple"] = 1,["banana"] = 2,["cherry"] = 3}for key, value in pairs(fruit) doprint(key.. ": ".. value)end
ipairs 遍历ipairs 主要用于遍历数组部分,也就是键为连续整数的部分,从 1 开始,遇到第一个 nil 就停止。
local numbers = {10, 20, 30, nil, 40}for index, value in ipairs(numbers) doprint(index.. ": ".. value)end
local text = "hello world hello lua"local words = {}-- 分割字符串for word in string.gmatch(text, "%w+") doif words[word] thenwords[word] = words[word] + 1elsewords[word] = 1endend-- 输出统计结果for word, count in pairs(words) doprint(word.. ": ".. count)end
local employees = {{id = 1, name = "Tom", department = "HR"},{id = 2, name = "Jane", department = "IT"},{id = 3, name = "Bob", department = "Finance"}}-- 查找 IT 部门的员工for _, employee in ipairs(employees) doif employee.department == "IT" thenprint(employee.name)endend
| 操作 | 方法 | 说明 |
|---|---|---|
| 创建表 | {} |
使用大括号创建一个空表 |
| 添加键值对 | table[key] = value |
向表中添加或修改键值对 |
| 访问值 | table[key] 或 table.key |
使用方括号或点号访问表中的值 |
| 遍历表 | pairs |
遍历表中的所有键值对 |
| 遍历数组部分 | ipairs |
遍历表中连续整数键的部分 |
通过以上的介绍和例子,我们可以看到 Lua 表作为关联数组的强大之处。它可以方便地存储和管理各种类型的数据,并且提供了丰富的操作方法。在实际的 Lua 编程中,合理运用表可以让代码更加简洁、高效。