Question

I have a program which aggregates for every user the total number of downloads performed with an aggregate of the total downloaded data in kb.

local table = {}
table[userID] = {5, 23498502}

My aim is that the output of the printTable function will produce the entire list of users ordered in descending order by the amount of kb downloaded v[2]

local aUsers = {}

...

function topUsers(key, nDownloads, totalSize)
    if aUsers[key] then
        aUsers[key][1] = aUsers[key][1] + nDownloads
        aUsers[key][2] = aUsers[key][2] + totalSize
    else
        aUsers[key] = {nDownloads, totalSize}
    end
end

function printTable(t)
    local str = ""

    -- How to sort 't' so that it prints in v[2] descending order?

    for k,v in pairs(t) do 
        str = str .. k .. ", " .. v[1] .. ", " .. v[2] .. "\n"
    end

    return str
end

...

Any ideas how could I do that?

Was it helpful?

Solution

You can get the keys into a separate table and then sort that table using the criteria you need:

local t = {
  a = {1,2},
  b = {2,3},
  c = {4,1},
  d = {9,9},
}
local keys = {}
for k in pairs(t) do table.insert(keys, k) end
table.sort(keys, function(a, b) return t[a][2] > t[b][2] end)
for _, k in ipairs(keys) do print(k, t[k][1], t[k][2]) end

will print:

d   9   9
b   2   3
a   1   2
c   4   1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top