4

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
2
  • What do you mean by sort? Tables with string keys are unsorted. To sort it you'd need to change the data structure. What is your expected result?
    – ahilsend
    Commented Jul 29, 2013 at 17:34
  • possible duplicate of Sort a Table[] in Lua
    – ahilsend
    Commented Jul 29, 2013 at 17:38

1 Answer 1

5

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
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.