Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How would I get the leader with the most kills in the game?

Asked by
zomspi 541 Moderation Voter
4 years ago
Edited 4 years ago

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?

1 answer

Log in to vote
1
Answered by
Ziffixture 6913 Moderation Voter Community Moderator
4 years ago
Edited 4 years ago

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!

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

Answer this question