简体   繁体   English

Lua用两个值对表排序?

[英]Lua Sort Table by Two Values?

So I have the following table: 所以我有下表:

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

How would I sort the sub-tables in the servers table, into a new array based on players first, and then number of visits, meaning that you don't sort by visits unless two tables have the same value for players. 如何将服务器表中的子表排序为一个新的数组,该数组首先基于玩家,然后根据访问次数排序,这意味着除非两个表对玩家的值相同,否则您不会按访问次数进行排序。

For example if the sorting code was put into a function called tableSort, I should be able to call the following code: 例如,如果将排序代码放入名为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 TIA

You have a hash, so you need to convert it to an array and then sort: 您有一个哈希,因此需要将其转换为数组,然后进行排序:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM