首页 > 代码库 > Lua的Table表使用例子(便于使用查询)
Lua的Table表使用例子(便于使用查询)
一、table.insert()
1.1
1 local countries = {"China", "England", "Brazil"}2 --尾插法(Pos不填,默认插入尾部)3 table.insert(countries, "France")4 --头插法(首部插入)5 table.insert(countries, 1, "Australia") 6 7 dump(countries)
二、table.remove()
2.1
1 local countries = {"China", "England", "Brazil", "England"}2 table.removeItem(countries, "England", true)3 dump(countries)
2.2
1 local countries = {"China", "England", "Brazil", "Australia"}2 --移除位置2上的元素(“England”)3 table.remove(countries, 2)4 --默认尾部删除元素5 table.remove(countries)6 dump(countries)
三、table.maxn()
3.1
1 local countries = {"China", "England", "Brazil", [7] = "Australia"}2 local Cars = {[-3] = "Benz", [-2] = "Toyota", [-1] ="LandRover"}3 --获取table的最大下标。如下标小于0,则返回04 print("Countries Maxn >> "..table.maxn(countries))5 print("Cars Maxn >> "..table.maxn(Cars))6 dump(countries)
四、table.concat()
4.1
1 local countries = {"China", "England", "Brazil","Australia"}2 --用“+”拼接table中的元素(table[1].."+"..table[2]..………….."+"..table[n])3 print("拼接: "..table.concat(countries, "+"))4 print("从Pos[3]开始拼接: "..table.concat(countries, "+", 3))
4.2
1 local countries = {"China", "England", "Brazil","Australia"}2 --table.concat(table, "X", began, end)3 --从began的位置,用"X"连接到end位置结束4 print("拼接: "..table.concat(countries, "+", 2, 3))
五、table.sort()
5.1
1 local countries = {"China", "England", "Brazil","Australia"}2 table.sort(countries)3 dump(countries)
5.2
1 local countries = {"China", "England", "Brazil","Australia"} 2 --自定义排序方式 3 myComparator = function(a, b) 4 if a > b then 5 return true 6 else 7 return false 8 end 9 end 10 table.sort(countries, myComparator)11 dump(countries)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。