先是一個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的數據進行遍歷發(fā)現數據不像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
二
local info = {fight = 100,name = "aa",camp = 1}
local info1 = {fight = 55,name = "bb",camp = 3}
local info2 = {fight = 55,name = "cc",camp = 2}
local allInfo = {}
table.insert(allInfo,info)
table.insert(allInfo,info1)
table.insert(allInfo,info2)
for i, v in pairs(allInfo) do
print(v.fight)
end
print("—————————排序———————————")
table.sort(allInfo,function(a,b)
--return (a.fight > b.fight)
if (a.fight ~= b.fight) then
return a.fight > b.fight
end
return a.camp < b.camp
end)
for i, v in pairs(allInfo) do
print(v.fight.." "..v.name)
end
100
55
55
—————————排序———————————
100 aa
55 cc
55 bb