local TheTable = {
Player1 = 3,
Player2 = 1,
Player3 = 10,
Player4 = 5,
}
function sortTable()
table.sort(TheTable, function(a, b)
return a > b
end)
end
sortTable()
Everybody is suggesting array sorting, which doesn’t work in this instance (you have a dictionary). The solution is simple: make an array from your dictionary, and sort the array. I’ll explain why using a dictionary here doesn’t work, but first - here’s a function for that:
local function sortDict(dict: { [any]: any })
local arr = {}
for key, value in pairs(dict) do
table.insert(arr, { Key = key, Val = value })
end
table.sort(arr, function(a, b)
return a.Val > b.Val
end)
return arr
end
The reason your output isn’t sorted is simple: dictionaries don’t have an order. They use a HashMap/HashTable (not sure which) behind the scenes, so they have some intrinsic ordering, but you can’t change it so that “Player2” appears before “Player1”, because it’s an unordered collection. I’m using programming terms commonly found in other programming languages. Read more here.
for _, playerData in ipairs(sortedTable)
-- Of course you'd have your own way of getting the labels here
local nameTextLabel: TextLabel, pointsTextLabel: TextLabel
nameTextLabel.Text = playerData.Key
pointsTextLabel.Text = playerData.Val
end
You can change the “Key” and “Val” throughout your code to be something like “Name” and “Points” - this will make reading it much easier, but it comes at the cost of restricting the function to the specific script (you can still use it of course, but it wouldn’t make sense).
You’re welcome! Please mark my post as a solution so other people can find the answer quickly (this is a rather common problem). Good luck with the game!
I found the problem, when using table.sort on dictionaries, it sorts the keys (Player1, Player2, Player3, Player4) and not the values (3, 1, 10, 5)
local TheTable = {
Player1 = 3,
Player2 = 1,
Player3 = 10,
Player4 = 5,
}
function sortTable()
local noKeys = {}
for player, value in TheTable do
local playerNum = string.gsub(player, "%a", "")
table.insert(noKeys, string.format("%dP%f", value, playerNum)
end
table.sort(noKeys, function(a, b)
return a > b
end)
for player, _ in TheTable do
local value
for _, v in noKeys do
local playerNum = string.split(v, "P")[3]
if "Player"..playerNum == player then
value = string.split(v, "P")[1]
break
end
end
player = value
end
noKeys = nil
return TheTable
end
edit: I post this and see a solution that spans just a few lines (oof)