gpt4 book ai didi

sorting - Lua 按两个值排序表?

转载 作者:行者123 更新时间:2023-12-05 01:21:05 24 4
gpt4 key购买 nike

所以我有下表:

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)

关于sorting - Lua 按两个值排序表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24894262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com