Lua按两个值排序表?

时间:2014-07-22 17:45:35

标签: sorting lua lua-table

所以我有下表:

servers = {"ProtectedMethod" = {name = "ProtectedMethod", visits = 20, players = 2}, "InjecTive" = {name = "InjecTive", visits = 33, players = 1}};

我如何将服务器表中的子表排序为基于玩家的新数组,然后是访问次数,这意味着您不会按访问排序,除非两个表具有相同的值播放器。

例如,如果将排序代码放入名为tableSort的函数中,我应该能够调用以下代码:

sorted = sort();
print(sorted[1].name .. ": " sorted[1].players .. ", " .. sorted[1].visits); --Should print "ProtectedMethod: 2, 20"
print(sorted[2].name .. ": " sorted[2].players .. ", " .. sorted[2].visits); --Should print "InjecTive: 1, 33"

TIA

1 个答案:

答案 0 :(得分:4)

你有一个哈希,所以你需要将它转换为一个数组,然后排序:

function mysort(s)
    -- convert hash to array
    local t = {}
    for k, v in pairs(s) do
        table.insert(t, v)
    end

    -- sort
    table.sort(t, function(a, b)
        if a.players ~= b.players then
            return a.players > b.players
        end

        return a.visits > b.visits
    end)
    return t
end

servers = {
    ProtectedMethod = {
        name = "ProtectedMethod", visits = 20, players = 2
    },

    InjecTive = {
        name = "InjecTive", visits = 33, players = 1
    }
}

local sorted = mysort(servers)
print(sorted[1].name .. ": " .. sorted[1].players .. ", " .. sorted[1].visits)
print(sorted[2].name .. ": " .. sorted[2].players .. ", " .. sorted[2].visits)