How to sort this lua table?

I have the following 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 ​​don't matter. For instance. First go to the Health panel, then Powerbar, and then go on to everyone else.

// edit.

Keys must be saved.

// edit # 2

Found a solution, thanks to everyone.

 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 
+4
source share
1 answer

You cannot sort the table of records because the records are ordered inside Lua, and you cannot change the order.

An alternative is to create an array in which each record is a table containing two fields (name and priority), and sort this table instead of the following:

 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 
+5
source

Source: https://habr.com/ru/post/1494102/


All Articles