先是一个key,value的键值对,实现思路是:先遍历获取到整个table的key值,然后对key值进行升序或降序,根据排序后的key值以此取出table里面的数据进行临时存储,得到排序后的table
测试地址:https://c.runoob.com/compile/66
skillgroup =
{
["101"] =
{
SkillGroupID = 101,
SkillType = 0,
Condition = 1,
},
["102"] =
{
SkillGroupID = 102,
SkillType = 1,
Condition = 1,
},
["103"] =
{
SkillGroupID = 103,
SkillType = 1,
Condition = 1,
},
["104"] =
{
SkillGroupID = 104,
SkillType = 1,
Condition = 2,
},
}
for i in pairs(skillgroup) do
print("直接输出:"..i)
end
-- 直接获取table的数据进行遍历发现数据不像list那样是直接索引取出排序好的,下面进行排序
-- 插入key
local keyTest ={}
for i in pairs(skillgroup) do
table.insert(keyTest,i)
end
-- 对key进行升序
table.sort(keyTest,function(a,b)return (tonumber(a) < tonumber(b)) end)
--对key进行降序
table.sort(keyTest,function(a,b)return (tonumber(a) > tonumber(b)) end)
-- 结果数据
local result = { }
for i,v in pairs(keyTest) do
table.insert(result,skillgroup[v])
print("id:"..v.." data:"..skillgroup[v].SkillGroupID)
end
打印输出
直接输出:103
直接输出:104
直接输出:101
直接输出:102
-- 升序结果
id:101 data:101
id:102 data:102
id:103 data:103
id:104 data:104
--降序结果
id:104 data:104
id:103 data:103
id:102 data:102
id:101 data:101