我有下一个结构 self.modules = { ["Announcements"] = { priority = 0, -- Tons of other attributes }, ["Healthbar"] = { priority = 40, -- Tons of other attributes }, ["Powerbar"] = { priority = 35, -- Tons of other attributes },} 我需要
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