Loop breaking early?

Hello everyone! I’m working on a bowling game in roblox, and I need all of the players to be removed from the session after the game is complete, the only issue is that when iterating through all of the players inside the session, it only removes the first index and I have found that this is due to the for loop breaking (Atleast I think). Below I will provide the code to the PlayerLeave function, and what is trying to remove all of the players inside the session. I have tried removing the PlayerLeave function from the loop and it iterates through all of the players without breaking. I’d also like to note that print #Session.Players does print out 2

PlayerLeave function:

function LaneService:PlayerLeave(playerId)
	local Session = LaneService:GetSessionByUserId(playerId)
	local playerInfo = Session.ScoreCards[playerId]
	if not playerInfo then return end

	local scoreCard

	if Session.GameInfo.Gamemode ~= "Practice" then
		playerInfo.scoreCard.Parent:Destroy()
	end
	local ScoringGui = Session.LaneModel.LaneDriver.ScoringScreen.SurfaceGui

	for i = #Session.Players, 1, -1 do
		if Session.Players[i] == playerId then
			table.remove(Session.Players, i)
			break
		end
	end

	for _, ball in pairs(Workspace:GetChildren()) do
		if ball:IsA("BasePart") and ball.Name == tostring(playerId) then
			ball:Destroy()
		end
	end

	if PlayerService:GetPlayerByUserId(playerId) then
		GameRunner.Remote.RemovePattern:FireClient(PlayerService:GetPlayerByUserId(playerId), Session.LaneModel.Lane.LaneSurface)
	end

	if #Session.Players == 0 then
		LaneService:ShutdownLane(Session, ScoringGui)
	elseif Session.CurrentPlayer == playerId then
		Session.LaneModel.LaneDriver.Cycle:Fire("Rerack")
		NextPlayer(Session)

		for _, Player in pairs(Session.Players) do
			GameRunner.Remote.CreateNotification:FireClient(PlayerService:GetPlayerByUserId(Player), {
				Type = "ERROR",
				Title = "Lane Reset",
				Body = string.format("%s has left the party, please wait for pinsetter to reset pins.", PlayerService:GetNameFromUserIdAsync(playerId))
			})
		end
	end
end

Loop that is removing all players:

function LaneService:GameComplete(Session)
	print(#Session.Players)
	for _, Player in pairs(Session.Players) do
		print(Player)
		LaneService:PlayerLeave(Player)

		print("after leave")
	end
end

LaneService:PlayerLeave removes a player from Session.Players which disrupts the iteration, causing the loop to skip over players. Try this:

function LaneService:GameComplete(Session)
    for i = #Session.Players, 1, -1 do
        local Player = Session.Players[i]
        LaneService:PlayerLeave(Player)
    end
end

Boy it’s crazy to think that the smallest things can cause the biggest issues. This resolved it, thank you so much!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.