Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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 comment

1 answer

✓ Accepted answer

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

5 comments

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

0

Never mind! It was my own mistake, thank you for the help!

0

No problem for the accept xd

0

thx bro

This discussion is preserved as it was. New answers, comments, and votes are closed.