This only works the first couple of times

So, I’ve made a script that checks who has the most points at the end of a round. The issue is that it normally records the first two wins correctly and then stops recording wins. I am trying to have it record a win every time the match ends for the player with the most points.


local function pointsChecker()
	for i, v in pairs(Players:GetPlayers())do
		local value = v.leaderstats.Points.Value
		if not highest then
			highest = value
		end
		if value > highest then
			highest = value
		end
	end
end

local function endGame()
	for i, v in pairs(Players:GetPlayers())do
		v.PlayerGui:WaitForChild("HillGui")
		v.PlayerGui.HillGui.TextLabel.Text = "The hill is neutral"
		pointsChecker()
		if v.leaderstats.Points.Value == highest then
			v.leaderstats.Wins.Value = v.leaderstats.Wins.Value + 1
		end
		v.leaderstats.Points.Value = 0
		v.TeamColor = BrickColor.new("Bright yellow")
		v:LoadCharacter()
	end
end

Try resetting thehighest variable to 0 before each call to pointsChecker. If it is left at a higher value than any of the players’ scores then nobody will be recognized as the winner.

You could also do it a little differently than using a global variable, and without having to call the function for every player:

local function getWinner()
	local _, winner = next(Players:GetPlayers())
	for _, player in ipairs(Players:GetPlayers()) do
		if (player.leaderstats.Points.Value > winner.leaderstats.Points.Value) then
			winner = player
		end
	end
	return winner
end

local function endGame()
	local winner = getWinner()
	if (winner) then
		winner.leaderstats.Wins.Value += 1
	end
	for i, v in pairs(Players:GetPlayers())do
		v.PlayerGui:WaitForChild("HillGui")
		v.PlayerGui.HillGui.TextLabel.Text = "The hill is neutral"
		v.leaderstats.Points.Value = 0
		v.TeamColor = BrickColor.new("Bright yellow")
		v:LoadCharacter()
	end
end
2 Likes

Well, now it records the wins wrong. For some reason it gave several players a win when only one player was receiving points?

@blokav I have a couple questions about your code just to further my understanding if you wouldn’t mind answering them. My first question is what next means in the “local _, winner = next(Players:GetPlayers())”. My second question is what does the += operator do, does it just take the current value and then add one to it? And if so, I’m not sure why that’s not listed with the other operators in the API?

next() is an interator that returns the next key/value pair in the table. Using ‘_’ for the key is just a coding style I use to show that the key variable is being thrown away. I used next because for a max search I needed some initial table value to compare the other values to and that is a short way to get any value.

+= is relatively new to Roblox. It’s a shorter way of adding something to a variable. These two lines are identical:

x = x + 3
x += 3

There is also -=, *=, /=, %=, etc. Even ..= for strings.