lua table 实现
时间: 2023-10-24 09:09:29 浏览: 175
Lua中的table是一种类似字典或关联数组的数据结构,它可以存储任何类型的值。
创建table:
1.使用{}来创建一个空的table
local table1 = {}
2.使用table.concat()函数创建一个table
local table2 = table.concat({"apple", "banana", "orange"})
3.使用索引号来创建一个table
local table3 = {1, 2, 3}
访问table:
1.使用索引号访问table中的元素
local fruit = {"apple", "banana", "orange"}
print(fruit[1]) -- output: apple
2.使用table.insert()函数向table中添加元素
local fruit = {"apple", "banana", "orange"}
table.insert(fruit, "pear")
print(fruit[4]) -- output: pear
3.使用table.remove()函数从table中删除元素
local fruit = {"apple", "banana", "orange"}
table.remove(fruit, 2)
print(fruit[2]) -- output: orange
4.使用for循环遍历table中的元素
local fruit = {"apple", "banana", "orange"}
for i, v in ipairs(fruit) do
print(i, v)
end
-- output:
-- 1 apple
-- 2 banana
-- 3 orange
5.使用#运算符获取table的长度
local fruit = {"apple", "banana", "orange"}
print(#fruit) -- output: 3
6.使用pairs()函数遍历table中的元素
local fruit = {apple = 1, banana = 2, orange = 3}
for k, v in pairs(fruit) do
print(k, v)
end
-- output:
-- apple 1
-- banana 2
-- orange 3
7.使用table.sort()函数对table中的元素进行排序
local fruit = {"apple", "banana", "orange"}
table.sort(fruit)
for i, v in ipairs(fruit) do
print(i, v)
end
-- output:
-- 1 apple
-- 2 banana
-- 3 orange
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)