Sorting values with table.sort

Hey there, fellow devs!

Ok ok. Before we start, I know this topic has been asked quite a lot. But I can’t seem to figure out (For my potato size brain)

So, I’ve a leaderstats folder that has 2 items (Rank, Touches). I want to figure out how can I sort player’s Rank value according to player’s Touches value. I’ll appreciate any help! Thanks!

I don’t get it. Can you give us an example?

Yeah you can do this by using a table and passing in the rank value as the index and the touches value as the key. Then just use table.sort on the table.

Some pseudo-code

local rankTable = {
--rank{index}, touches{key)
    {5, 35}, 
    {7, 30},
    {2, 40}
}

table.sort(rankTable, function(a,b) return a[2] > b[2] end)

for _, v in pairs(rankTable) do
    print('rank: '..v[1]..' | '..'value: '..v[2])
end
1 Like

Whoops, went offline. Okay, so let me explain. Actually to understand better I named it touches in a normal baseplate but well, I don’t that works.:roll_eyes: Anyways, I was making an FPS game where in the tab leaderboard it will rank the players with the amount of kills they have. Buuuuut, since I don’t know how to use table.sort() properly, I’ve no idea what I was doing. (Hopefully that made sense)

Thanks for the help guys! I just figured it out!

Just for anybody who wants to see the script, here it is (Please learn from it, don’t copy-paste):

local function Ascend(x --[[Table]], indexing --[[Bool]], index --[[Number]])
	table.sort(x, function(a, b)
		if indexing then
			return a[index] > b[index]
		else
			return a > b
		end
	end)
end

local function Descend(x --[[Table]], indexing --[[Bool]], index --[[Number]])
	table.sort(x, function(a, b)
		if indexing then
			return a[index] < b[index]
		else
			return a < b
		end
	end)
end

This is just a part, you can ‘for’ loop and print out the table you have!

Had a question. Why can’t we do like {Name = "Xx_FROSTBITExX", Kills = 10}? It errors saying something like nil > nil