通过两个值对Lua表进行排序?

4

所以我有以下表格:

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


请再明确一下问题。您有 visits = 20, players = 2,而 sorted[1].players, sorted[1].visits 给出的是 20, 2 - hjpotter92
抱歉,我搞错了。应该是“2, 20”,我会更新帖子的。 - ProtectedMethod
1个回答

8
您有一个哈希表,所以您需要将其转换为数组,然后进行排序:
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)

应该可以工作。非常感谢!;) - ProtectedMethod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接