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

How would I find the player with the highest leaderstats value?

Asked by 5 years ago

I am attempting to find a player in my game who has the highest leaderstats value, known as 'eggsFound'

_G.eggHunters = {}

for i,v in pairs(game.Players:GetPlayers()) do
    if v ~= nil then
        table.insert(_G.eggHunters, v.Name)
    end
end

for _, v in pairs(_G.eggHunters) do

end

This is all I have right now, I'm unsure of what else I can try to find the person with the highest leaderstats value known as 'eggsFound', any help would be appreciated! Thanks!

1 answer

Log in to vote
2
Answered by
hellmatic 1523 Moderation Voter
5 years ago
Edited 5 years ago

You can do this using tables, table.insert() and table.sort():

_G.eggHunters = {}

for i,v in pairs(game.Players:GetPlayers()) do
    if v ~= nil then
        table.insert(_G.eggHunters, v) -- store the player instead of their name
    end
end

local function getHighestEggsFound()
    local TempTable = {} -- this table would be used to store each player's eggs found number
    for _, player in pairs(_G.eggHunters) do
        local leaderstats = player:FindFirstChild("leaderstats")
        local eggsFoundValue = (leaderstats and leaderstats:FindFirstChild("eggsFound")
        if eggsFoundValue then 
            -- 'table.insert(x, y, z)' has 3 arguments. x = table(array), y = number position (optional), z = variable/object/instance your adding to the table
            table.insert(
                TempTable,
                {
                    player,
                    eggsFoundValue.Value
                }
            }
        end
    end
    if #TempTable >= 1 then 
         --'table.sort(x, y)' has 2 arguments. x = table(array), y = function (optional)
        table.sort(
            TempTable,
            function(a, b) -- 'a' and 'b' is the data/table inserted into the TempTable
                -- we are comparing the distances and ordering them from greatest to least
                -- so we get the data's second value a[2] and b[2] which is the eggs found number and compare them
                return a[2] > b[2]
            end
        )
        print(
            TempTable[1][1], -- player
            "has the most with",
            TempTable[1][2], -- eggs found number
            "eggs found!"
        )
    end
end
0
Hi there! Thank you for this answer, however I have put this into my code and the `if #TempTable >= 1 then` doesn't seem to run, and neither does the code after it. I have attempted to fix it however I am unsure Cynmorphic 0 — 5y
0
Never mind! It was my own mistake, thank you for the help! Cynmorphic 0 — 5y
0
No problem for the accept xd User#24403 69 — 5y
0
thx bro hellmatic 1523 — 5y
Ad

Answer this question