Sorting 如何对这个lua表进行排序?

Sorting 如何对这个lua表进行排序?,sorting,lua,lua-table,Sorting,Lua,Lua Table,我有下一个结构 self.modules = { ["Announcements"] = { priority = 0, -- Tons of other attributes }, ["Healthbar"] = { priority = 40, -- Tons of other attributes }, ["Powerbar"] = { priority = 35,

我有下一个结构

self.modules = {
    ["Announcements"] = {
        priority = 0,
        -- Tons of other attributes
    },
    ["Healthbar"] = {
        priority = 40,
        -- Tons of other attributes
    },
    ["Powerbar"] = {
        priority = 35,
        -- Tons of other attributes
    },
}
我需要按优先级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

你说的排序是什么意思?带有字符串键的表未排序。要对其进行排序,您需要更改数据结构。您的预期结果是什么?可能重复的