簡體   English   中英

Lua用兩個值對表排序?

[英]Lua Sort Table by Two Values?

所以我有下表:

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

您有一個哈希,因此需要將其轉換為數組,然后進行排序:

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