Help i don't know what i am doing

how do i stop this function if player suddenly leaves mid voting? it continues to vote and picks map afterwards which results in a free win. please help heres the script:

local function round()
while true do

	local requiredPlayers = 2
	local lobby = {}
	local Playingteam = script.Parent.Parent.Teams.Playing
	local Lobbyteam = script.Parent.Parent.Teams.Lobby

	for i, plr in pairs(game.Players:GetChildren()) do

		if plr.Team.Name == "Lobby" then
			table.insert(lobby, plr.Name)
			print("inserted player")
		end	
	end
	
	repeat
		wait(1)
		staus.Value ="Not enough players to start the game! minimum " ..requiredPlayers.." required"
	until #game.Players:GetChildren() >= requiredPlayers
	
	if #lobby == 1 then
		inRound.Value = false
	else
		inRound.Value = true

	end
	
	for i = intermission, 0, -1 do

		staus.Value = "Voting ends in "..i.." seconds"
		

		wait(1)

	end
1 Like

To stop the voting process if a player leaves mid-voting, you can use the PlayerRemoving event to remove the player from the lobby table and check if the number of players in the lobby is still greater than or equal to requiredPlayers . If not, you can exit the function and prevent the map from being picked. Here’s an example modification to your code:

local function round()
    while true do
        local requiredPlayers = 2
        local lobby = {}
        local Playingteam = script.Parent.Parent.Teams.Playing
        local Lobbyteam = script.Parent.Parent.Teams.Lobby

        for i, plr in pairs(game.Players:GetChildren()) do
            if plr.Team.Name == "Lobby" then
                table.insert(lobby, plr.Name)
                print("inserted player")
            end
        end

        repeat
            wait(1)
            staus.Value = "Not enough players to start the game! minimum " ..requiredPlayers.." required"
        until #lobby >= requiredPlayers or inRound.Value == false

        if #lobby == 1 then
            inRound.Value = false
        else
            inRound.Value = true
        end

        if inRound.Value == false then
            break -- exit the while loop if inRound is false
        end

        for i = intermission, 0, -1 do
            staus.Value = "Voting ends in "..i.." seconds"
            wait(1)

            -- Check if any player has left the game
            for j, plr in pairs(lobby) do
                if not game.Players:FindFirstChild(plr) then
                    table.remove(lobby, j)
                    if #lobby < requiredPlayers then
                        staus.Value = "Not enough players to start the game! minimum " ..requiredPlayers.." required"
                        return -- exit the function if the number of players is less than required
                    end
                end
            end
        end
    end
end