How to sort players by their numbered rank in a survival round?

I am making a leaderboard system where it sorts a player’s rank based on how long they survived in the round they played in. I can already set the player’s rank but it is set as a value in a dictionary table under the player.

So here’s the question: How do I sort a table based off a player’s rank. Sorry for not understanding much table terminology

Basically I want to go from this…

local leaderboardList = {
[player1] =  3,
[player2] =  1,
[player3] =  2
}

to this

-- The rank is the first value in each player, and I want to sort the 'leaderboardList' table like this
local leaderboardList = {
[player2] =  1,
[player3] =  2,
[player1] =  3
}

If you can help, please reply!

3 Likes

You can use table.sort to sort this table.

table.sort(leaderboardList, function(elementA, elementB)
    --the elements are the values of the keys. We can compare them to sort the table.
    return elementA > elementB
end)
2 Likes

Just to put a resource link How to use table.sort? methods the same thing that the fellow above me stated and has examples that might prove useful

fyi, you cannot sort dictionaries. You would have to use arrays:

local leaderboardList = {
    {
        Player = player1,
        Points = 3
    }
}

table.sort(leaderboardList, function(a, b)
    return a.Points > b.Points
end)

I just tested sorting a dictionary and it worked fine…

edit: 5th test in and the larger sample size worked. this is a smaller sample size

seems like the keys in the dictionary get re-arranged

No it doesn’t, dictionaries don’t have orders. Your sample size is most likely very small and your prints are coincidentally in the right order.

I made sure my items were in the complete wrong order. I don’t understand why it would only work for smaller dictionaries and not larger ones.

It doesn’t. Run this code and you’ll see the behavior:

--!strict

local function generateRandomDictionary(count: number): {[string]: number}
	local dictionary: {[string]: number} = {}
	
	for i: number = 1, count do
		dictionary[tostring(i)] = math.random(1, 100)
	end
	
	return dictionary
end

local randomDictionary: {[string]: number} = generateRandomDictionary(100)

-- this will typecheck error as it is expecting an array
table.sort(randomDictionary, function(a: number, b: number): boolean
	return a > b
end)

for index: string, value: number in randomDictionary do
	print(index, value)
end