How do i find the highest value with a script?

okay so i have 2 players with different stats as shown:
image

im wondering how i could make a script to search every player and return the highest kill count then 2nd 3rd 4th etc

help pls

You can use table.sort function to do this just create a table looking like this

{
[“takticiadam”] = takticiadamskillshere
[“roblox”] = robloxskills here
}

then you can use table.sort on it.

if you wanted an array with the players sorted correctly then

local Players = game:GetService("Players")

local function sortPlayers()
	local sorted = {unpack(Players:GetPlayers())}

	table.sort(sorted, function(p1, p2)
		return p1.leaderstats.Kills.Value > p2.leaderstats.Kills.Value
	end)

	return sorted
end

and you’d use it like

for i, player in ipairs(sortPlayers()) do
    print(string.format("%d. %s", i, player.Name))
end

if player A had 7 kills, B had 14 kills and C had 9 kills then the output would look like this

1. Player B
2. Player C
3. Player A

You may want to have checks if the player has their leaderstat stuff loaded in.


If you are wondering how table.sort works then here is a quick overview:

local numberArray = {7, 9, 3, 4, 2}
table.sort(numberArray) -- second arg is optional
print(unpack(numberArray)) --> 2, 3, 4, 7, 9

table.sort(tbl)

yields the same results as

table.sort(tbl, function(a, b)
    return a < b
end)

if the return value of the callback you provided as the second arg is true then a is placed before b

2 Likes
		return p1.leaderstats.Kills.Value > p2.leaderstats.Kills.Value
	end)

will this only search through player1 and player2?

the game will have more then 2 players with different names

This is the compare check that table.sort() will use
I believe table.sort() uses the quick sort algorithm

It took me some time to understand but this worked thanks!