Script unexpectedly stops at a certain point

I have this section of a script that gives each player a role at the start of the round. However, the script unexpectedly stops between prints b and cand roles are never assigned. I’m not sure why, and no error is displayed to give a reason why. If anyone could tell me why it stops it would be appreciated.


local function chooseRoles()
	print("a")
	
	local getPlayers = players:GetPlayers()
	
	local playersWithOtherRoles = {}

	local numOfPlrsWithRequiredRole = 0

	if #getPlayers < #requiredRoles then
		return
	end
	
	print("b")

	for i, Role in ipairs(requiredRoles) do
		local randomPlayer

		repeat
			wait()
			randomPlayer = getPlayers[math.random(1, #getPlayers)]
		until not randomPlayer.Role or randomPlayer.Role.Value == ""

		randomPlayer.Role.Value = requiredRoles[i]
		numOfPlrsWithRequiredRole += 1
		print(randomPlayer.Name .. ": " .. randomPlayer.Role.Value)
		randomPlayer.Character:MoveTo(game.Workspace[randomPlayer.Role.Value.."_Spawn"])
	end
	
	print("c")

	for i, player in pairs(players:GetChildren()) do
		local alreadyHasRole = false
		for j, Role in ipairs(requiredRoles) do
			if player.Role.Value == requiredRoles[j] then
				alreadyHasRole = true
			end
		end
		if not alreadyHasRole then
			table.insert(playersWithOtherRoles, player.Name)
		end
	end
	
	print("d")

	for i, checkRole in ipairs(playersWithOtherRoles) do
		local player = players:FindFirstChild(checkRole)
		if player then
			local randomOtherRole = math.random(1, #otherRoles)
			player.Role.Value = otherRoles[randomOtherRole]
			print(player.Name.. ": ".. player.Role.Value)
			player.Character:MoveTo(game.Workspace[player.Role.Value.."_Spawn"])
		end
	end
	print("e")


end

1 Like

Try adding some print statements. Something like so:

		repeat
			wait()
			randomPlayer = getPlayers[math.random(1, #getPlayers)]
			
			print("randomPlayer =", randomPlayer)
			print("randomPlayer.Role =", randomPlayer.Role)
			
		until not randomPlayer.Role or randomPlayer.Role.Value == ""

print results:

randomPlayer = PizzaArmy333
randomPlayer.Role = Spectators

*i assume you meant the value of the role, so i did role.Value instead of role

i am also doing this testing with one player

It’s important to remember that for loops block the code that’s written below them from running before it finishes iterating, so in your case I can think of two possible problems:

  1. The repeat loop could be running indefinitely, which would prevent the for loop from continuing
  2. If there are multiple roles within your game, you might need to test using the local server, which is found in Studio’s TEST tab