Lua中的table
是一种非常灵活的数据结构,它可以用来模拟数组、字典、集合等多种数据结构。table
以键值对的形式存储数据,其中键可以是任何类型,但通常是数字或字符串。以下是table
的一些基本用法和项目示例。
table
的基本操作
创建和初始化table
-- 创建一个空的table
local myTable = {
}
-- 直接初始化一个带有值的table
local myTable = {
key1 = "value1", key2 = "value2"}
AI 代码解读
访问和赋值
-- 给table赋值
myTable["key3"] = "value3"
-- 访问table中的值
local value = myTable["key3"]
print(value) -- 输出:value3
AI 代码解读
数组式的使用
-- 数组式的赋值
myTable[1] = "first element"
myTable[2] = "second element"
-- 数组式的访问
local firstElement = myTable[1]
print(firstElement) -- 输出:first element
AI 代码解读
table
的遍历
使用ipairs
遍历数组
for index, value in ipairs(myTable) do
print(index, value)
end
AI 代码解读
使用pairs
遍历所有键值对
for key, value in pairs(myTable) do
print(key, value)
end
AI 代码解读
完整项目示例
假设我们正在创建一个简单的通讯录应用,我们将使用table
来存储联系人信息,并提供添加、查找和显示所有联系人的功能。
-- 创建一个空的table来存储联系人
local contacts = {
}
-- 添加联系人函数
function addContact(name, phoneNumber)
table.insert(contacts, {
name = name, phone = phoneNumber})
end
-- 查找联系人函数
function findContact(name)
for i, contact in ipairs(contacts) do
if contact.name == name then
return contact
end
end
return nil
end
-- 显示所有联系人函数
function displayContacts()
print("Contacts:")
for i, contact in ipairs(contacts) do
print(string.format("%d: %s - %s", i, contact.name, contact.phone))
end
end
-- 添加一些联系人
addContact("Alice", "123-456-7890")
addContact("Bob", "987-654-3210")
-- 查找一个联系人
local contact = findContact("Alice")
if contact then
print(string.format("Found contact: %s - %s", contact.name, contact.phone))
else
print("Contact not found.")
end
-- 显示所有联系人
displayContacts()
AI 代码解读