How would I loop through every player in a table then make a variable for the player with the highest amount of kills, and then if someone else overtakes their place the variable changes to that player?
How would I get the leader with the most kills in the game?
1 answer
You can use the table.sort function. By supplying a predication argument, you can tell table.sort how it should sort the array based on each value compared: a, b. By creating our predication function and filtering with the > greater-than operator, we can organize a table from highest-to-lowest elements.
Assuming you have a Leaderboard containing a Kills ValueObject, we can use it's information as our sort base.
local Players = game:GetService("Players"):GetPlayers()
local KillsTable = {} do
for _,Player in pairs(Players) do
local Kills = Player:FindFirstChild("Kills")
table.insert(KillsTable, Kills.Value)
end
table.sort(KillsTable, function(a, b)
return a > b
end)
end
print(KillsTable)
Since the first element is the highest, we can find the highest by asking for numerical index one
local HighestKills = KillsTable[1]
This will give us the highest kill-number, but not the player with it, to do that, we can pair the Player with their Kills value in it's own array and store it instead of Kills alone. Since we're inserting a table with two elements, we have to recoordinate the predication function to filter for index 1 to match the Kills properly again.
local Players = game:GetService("Players"):GetPlayers()
local KillsTable = {} do
for _,Player in pairs(Players) do
local Kills = Player:FindFirstChild("Kills")
table.insert(KillsTable, {Kills.Value, Player})
end
table.sort(KillsTable, function(a, b)
return a[1] > b[1]
end)
end
local HighestKillCount = KillsTable[1][1]
local PlayerWithHighestKills = KillsTable[1][2]
print(PlayerWithHighestKills.Name.." has the highest number of kills: "..HighestKillCount)
Remember to accept this answer if it helps!
This discussion is preserved as it was. New answers, comments, and votes are closed.

4 comments
Well, it is a leaderstat, but an invisible leaderstat called leaderstatsA, also, how do I put all this in 1 script?
The code above will do everything you need, just change the Kills variable allocation to a leaderstatA ValueObject that handles the Kills
So it would be local kills = Player:FindFirstChild("LeaderstatsA"):FindFirstChild("Kills")
Mhm!