次のLuaテーブルが変数に格納されていますT
:
{
["mn"] = { ["index"] = 7, ["key"] = "mn", ["score"] = 0 },
["kl"] = { ["index"] = 6, ["key"] = "kl", ["score"] = .4 },
["ef"] = { ["index"] = 3, ["key"] = "ef", ["score"] = .3 },
["ab"] = { ["index"] = 1, ["key"] = "ab", ["score"] = 0 },
["cd"] = { ["index"] = 2, ["key"] = "cd", ["score"] = .1 },
["gh"] = { ["index"] = 4, ["key"] = "gh", ["score"] = 0 },
["ij"] = { ["index"] = 5, ["key"] = "ij", ["score"] = .2 }
}
テーブルのすべての内部テーブルをT
次のように並べ替えたいと思い
ます。1。上位のテーブルscore
が一番上に配置されます。
2.等しいテーブルscore
は、でソートされますindex
。
したがって、ソート後、次のシーケンシャルテーブルが出力に生成されます。
{
[1] = { ["index"] = 6, ["key"] = "kl", ["score"] = .4 }, -- highest "score"
[2] = { ["index"] = 3, ["key"] = "ef", ["score"] = .3 },
[3] = { ["index"] = 5, ["key"] = "ij", ["score"] = .2 },
[4] = { ["index"] = 2, ["key"] = "cd", ["score"] = .1 },
[5] = { ["index"] = 1, ["key"] = "ab", ["score"] = 0 }, -- lowest "score", lowest "index"
[6] = { ["index"] = 4, ["key"] = "gh", ["score"] = 0 }, -- when scores are the same, sort by their "index" instead
[7] = { ["index"] = 7, ["key"] = "mn", ["score"] = 0 } -- lowest "score", highest "index"
}
このLuaテーブルソートを実行する方法は?
最初にハッシュをテーブルに変換してから、同じスコアを持つ要素をscore
(降順)、次にindex
(昇順)で並べ替えるカスタム並べ替え関数を使用して、そのテーブルの要素を並べ替える必要があります。
このようなものが機能するはずです:
local hash = {
["mn"] = { ["index"] = 7, ["key"] = "mn", ["score"] = 0 },
["kl"] = { ["index"] = 6, ["key"] = "kl", ["score"] = .4 },
["ef"] = { ["index"] = 3, ["key"] = "ef", ["score"] = .3 },
["ab"] = { ["index"] = 1, ["key"] = "ab", ["score"] = 0 },
["cd"] = { ["index"] = 2, ["key"] = "cd", ["score"] = .1 },
["gh"] = { ["index"] = 4, ["key"] = "gh", ["score"] = 0 },
["ij"] = { ["index"] = 5, ["key"] = "ij", ["score"] = .2 }
}
local tbl = {}
for _,v in pairs(hash) do
table.insert(tbl, v)
end
table.sort(tbl, function(a,b)
return a.score > b.score or a.score == b.score and a.index < b.index
end)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加