I posted a question on this yesterday, but didn't tell the whole story. (I also messed up when writing the question and put :GetChildren
instead of :GetChildren()
, leading a user to think that was my mistake)
This is cut out of a larger script:
players = game.Players:GetChildren() function pick() repeat local invisiblechoice1 = players[math.random(1, #players)] -- Whenever I test it always gets stuck here. What's the problem? I examined it on its own and it worked fine. game.Workspace.Inv1.Value = invisiblechoice1.Name invisiblechoice1.Inv = true -- these are unrelated to my question, they ARE valid values in the player invisiblechoice1.Invs = true local invisiblechoice2 = players[math.random(1, #players)] game.Workspace.Inv12.Value = invisiblechoice2.Name invisiblechoice2.Inv = true invisiblechoice2.Invs = true until invisiblechoice1 ~= invisiblechoice2 end pick()
So what is going wrong? I set up my game with Google Analytics after being annoyed for a while (4 players are required to play and it is a 2 man pick system, so I was testing outside of studio), and got this back:
"Workspace.GameScript:42: bad argument #2 to 'random' (interval is empty) | Workspace.GameScript, line 42"
So what does this mean, and how can I fix it? If you can answer it would be very appreciated!
What @LuigiMario865 is also a good point, but that's not the problem here.
The problem here is that you're doing math.random(1,0)
when there are 0 players. There are no numbers between 1 and 0 (in that order) so it errors.
A solution would be to start for enough players at the start of the repeat-block:
local Players = game:GetService("Players") -- cleaner and a bit faster, not that speed matters function pick() while #Players:GetPlayers() < 4 do Players.PlayerAdded:wait() end
Also, not related to your question, but you can pick the same player for both choices. You could fix this by removing the player from the table when you pick him:
local players = Players:GetPlayers() -- table contains {A,B,C,D} local playerA = table.remove(players,math.random(1,#players)) -- if C is taken, table contains {A,B,D} local playerB = table.remove(players,math.random(1,#players))
This is a lot better than your repeat-statement. (although that was also a nice idea to fix that)
I found your error! C:
players = game.Players:GetChildren()
Instead of getting the children of Players, you'd want to change it to....
players = game.Players:GetPlayers()