How to sort this lua table?

梦想的初衷 提交于 2021-02-07 19:05:07

问题


I have next structure

self.modules = {
    ["Announcements"] = {
        priority = 0,
        -- Tons of other attributes
    },
    ["Healthbar"] = {
        priority = 40,
        -- Tons of other attributes
    },
    ["Powerbar"] = {
        priority = 35,
        -- Tons of other attributes
    },
}

I need to sort this table by priorty DESC, other values does not matter. E.g. Healthbar first, then Powerbar, and then going all others.

// edit.

Keys must be preserved.

// edit #2

Found a solution, thanks you all.

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

回答1:


You can't sort a records table because entries are ordered internally by Lua and you can't change the order.

An alternative is to create an array where each entry is a table containing two fields (name and priority) and sort that table instead something like this:

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

Output:

1       Healthbar       40
2       Powerbar        35
3       Announcements   0


来源:https://stackoverflow.com/questions/17930112/how-to-sort-this-lua-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!