lua中table的常用方法理解和使用

-- --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,"|"))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值