Je la table Lua suivante stockée dans la variable T
:Comment trier les tables internes dans Lua par leur "score", puis "index"?
{
["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 }
}
Je veux trier toutes les tables internes de la table T
de la façon suivante:
1. Les tableaux avec plus score
sont mis sur haut.
2. Les tables avec score
sont triées par leur index
.
Ainsi, après le tri, la table séquentielle suivante doit être produit sur la sortie:
{
[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"
}
Comment accomplir ce genre de table Lua?
https://devdocs.io/lua~5.3/index#pdf-table.sort – hjpotter92
Je comprends que je dois utiliser fonction 'table.sort' Lua .Mais, je ne sais pas comment l'utiliser pour ce cas. – Pojat