[英]How to sort this lua table?
我有下一個結構
self.modules = {
["Announcements"] = {
priority = 0,
-- Tons of other attributes
},
["Healthbar"] = {
priority = 40,
-- Tons of other attributes
},
["Powerbar"] = {
priority = 35,
-- Tons of other attributes
},
}
我需要通過priorty DESC對此表進行排序,其他值無關緊要。 例如Healthbar,然后是Powerbar,然后去其他所有人。
//編輯
必須保留密鑰。
//編輯#2
找到了解決方案,謝謝大家。
local function pairsByPriority(t)
local registry = {}
for k, v in pairs(t) do
tinsert(registry, {k, v.priority})
end
tsort(registry, function(a, b) return a[2] > b[2] end)
local i = 0
local iter = function()
i = i + 1
if (registry[i] ~= nil) then
return registry[i][1], t[registry[i][1]]
end
return nil
end
return iter
end
您無法對記錄表進行排序,因為Lua在內部對條目進行排序,您無法更改順序。
另一種方法是創建一個數組,其中每個條目都是一個包含兩個字段( 名稱和優先級 )的表,並對該表進行排序,而不是這樣:
self.modulesArray = {}
for k,v in pairs(self.modules) do
v.name = k --Store the key in an entry called "name"
table.insert(self.modulesArray, v)
end
table.sort(self.modulesArray, function(a,b) return a.priority > b.priority end)
for k,v in ipairs(self.modulesArray) do
print (k,v.name)
end
輸出:
1 Healthbar 40
2 Powerbar 35
3 Announcements 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.