Search code examples
lualua-table

Order Lua Table in Descending Order (Highest to Lowest)


I've tried everything to try to get this lua table to order from highest to lowest. I've looked at other stackoverflow threads, all across the web, and it's not working.

local DTable = {}
local SC = 0
for e,q in pairs(LastATP) do
  local CT = {e,q}
  SC = SC + 1
  table.insert(DTable, SC, CT)
end         

table.sort(DTable, function(a, b) return a[2] < b[2] end)

"E" is a random key, ex) dxh3qw89fh39fh - whilst q is a number. Please help. I've tried everything. When I try to iterate through the sorted table I also use "for i,v in ipairs(DTable)" - Responses soon, please!


Solution

  • table.sort's comparator acts like < -- it uses it to arrange the values in the list so that the smallest is first and the largest is last. This looks like

    first < second < third < .... < last

    If you want to reverse that order, you should give it a "> operation" instead:

    first > second > third > .... > last

    -- Sort `DTable` by the second value in the pair, decreasing
    table.sort(DTable, function(a, b) return a[2] > b[2] end)
    

    In your question, you said the values like q were numbers. If they are in fact strings but you want to sort them as numbers, you should use tonumber to convert them:

    -- Note that keeping track of "SC" is not necessary, it is just the
    -- length of DTable, which is where table.insert inserts by default
    table.insert(DTable, {e, tonumber(q)}))