How to sort this lua table?
lua, lua-table, sorting
Solution
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
Problem
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 ```