-- --lua中table的使用
local tab = {}
--table.insert(list: table, pos: integer, value: any)
--table 是一个table
--pos 位置
--value 插入的值,可选
for i = 1, 10, 1 do
table.insert(tab,i)
end
--table.remove( list, [pos,] )
--list table
--移除指定位置
table.remove (tab, 2)
for index, value in ipairs(tab) do
print("remove=",value)
end
--table.sort(list: table, comp: function(a: any, b: any): boolean)
--升序排序
--comp 比较方法
table.sort(tab)
for index, value in ipairs(tab) do
print("sort=",value)
end
--增加函数方法比较
local tbl = {
{id = 1, name = "华为", price = 8888.00, quality = 90},
{id = 2, name = "小米", price = 2999.00, quality = 85},
{id = 3, name = "苹果", price = 9999.00, quality = 89},
{id = 4, name = "荣耀", price = 2500.00, quality = 79},
{id = 5, name = "vovo", price = 3666.00, quality = 82}
}
print("-------按price--------------")
table.sort(tbl, function(a, b)
-- 按price降序排序
return a.price > b.price
end)
for _, v in pairs(tbl) do
print(string.format("id = %d, name = %s, price = %s, quality = %d", v.id, v.name, v.price, v.quality))
end
print("-------按quality--------------")
table.sort(tbl, function(a, b)
-- 按quality降序排序
return a.quality > b.quality
end)
for _, v in pairs(tbl) do
print(string.format("id = %d, name = %s, price = %s, quality = %d", v.id, v.name, v.price, v.quality))
end
--table.concat(list: table, sep: string, i: integer, j: integer)
--连接字符串
--sep分割符
local fruits = {"banana","orange","apple"}
print("concat = ", table.concat(fruits,"|"))
local shu = {1,2,3}
print("concat = ", table.concat(shu,"|"))