Invalid argument #2 to 'random' (interval is empty)

Heyo Devforum! I have been making a round system for my game where I choose a random player from all of the players in the game, but I ran into the error: 10:17:59.766 - ServerScriptService.RoundSystem:12: invalid argument #2 to ‘random’ (interval is empty). I have searched this error on the Devforum and found that this error appears when the second argument of math.random is less than the first argument. This doesn’t make sense to me though because my game makes it so that the round system runs only when there is more than one player in my game. Please take a look.

Script:

local playertable = game.Players:GetPlayers()

local status = game.ReplicatedStorage.Status

while true do
	if game.Players.NumPlayers > 1 then
		print("Yes")
		for i = 30, 1, -1 do
			wait(1)
			status.Value = "Round starting in: "..i
		end
		local rancontrol = math.random(1, #playertable)
		local chosencontrol = playertable[rancontrol]
		print("Chosen: "..chosencontrol.Name)
		chosencontrol.Team = game.Teams["Controller"]
		for i, player in pairs(playertable) do
			if player ~= chosencontrol then
				player.Team = game.Teams.Players
			end
		end
		print("Done")
	else
		wait(1)
		status.Value = "Waiting for 2 or more players"
	end
end
2 Likes

why are u making your life hard ? by using For and not just wait

1 Like

I am using the for loop to count down when the round will start. I am pretty sure you can’t do this with wait.

1 Like

other way to do it its

for I = 1, 30 do
    wait(1)
    print(30 - i.." secounds")
end
1 Like

Thank you for your suggestion but that is not the issue here. The for loop works fine, but it is what is after the for loop that doesn’t work.

2 Likes
local TotalPlayers = 0

for _, Player in pairs(game.Players:GetPlayers() do
       TotalPlayers = TotalPlayers + 1
end

use that For rancontrol and then use to chose random player
1 Like

Try this


while true do
local playertable = game.Players:GetPlayers()

local status = game.ReplicatedStorage.Status

	if game.Players.NumPlayers > 1 then
		print("Yes")
		for i = 30, 1, -1 do
			wait(1)
			status.Value = "Round starting in: "..i
		end
		local rancontrol = math.random(1, #playertable)
		local chosencontrol = playertable[rancontrol]
		print("Chosen: "..chosencontrol.Name)
		chosencontrol.Team = game.Teams["Controller"]
		for i, player in pairs(playertable) do
			if player ~= chosencontrol then
				player.Team = game.Teams.Players
			end
		end
		print("Done")
	else
		wait(1)
		status.Value = "Waiting for 2 or more players"
	end
end
4 Likes

This is the solution as getting the # of players only runs once. Putting it in the loop will correct the issue as it constantly checks the number of players. You could even only update # of players when someone joins or leaves as not to spam check getting players.

2 Likes

Yes, the issue is that you are getting the number of players before there are any to begin with.

1 Like