Error: bad argument #2 to 'random' (interval is empty)
I am trying to make a 1v1 game and choosing 2 opponents and making sure they are both not the same person, can someone help?
Code:
wait(1) local players = game.Players:GetPlayers() local maps = game:GetService("ServerStorage").Maps:GetChildren() local runningmaps = workspace:WaitForChild("RunningMaps") function hint(text) for i, player in pairs(players) do player:WaitForChild("PlayerGui").MainGui.hint.Text = tostring(text) end end function shout(text) for i, player in pairs(players) do player:WaitForChild("PlayerGui").MainGui.shout.Text = tostring(text) end end while true do hint("Welcome to Sword Fighting Practice!") wait(3) hint("Intermission: 15 seconds") for i=15,1,-1 do hint("Intermission: " ..i.. " seconds") if i < 2 then hint("Intermission: " ..i.. " second") end wait(1) end hint("") shout("Choosing a random map...") randommap = math.random(1,#maps) mapchosen = maps[randommap] wait(3) shout("Map Chosen: " ..mapchosen.Name) wait(3) local mapClone = mapchosen:Clone() mapClone.Parent = runningmaps local opponent1 = players[math.random(1,#players)] -- Error starts here local opponent2 = players[math.random(1,#players)] local spawns = mapClone:WaitForChild("Spawns") if opponent1.Character.Name ~= opponent2.Character.Name and opponent2.Character.Name ~= opponent1.Character.Name then print("True") for i,v in pairs(opponent1, opponent2) do if spawns then opponent1.Character:WaitForChild("Torso"):MoveTo(spawns.Position) end end else repeat local opponent1 = players[math.random(1,#players)] local opponent2 = players[math.random(1,#players)] wait() until opponent1.Name ~= opponent2.Name and opponent2.Name ~= opponent1.Name end --for i,v in pairs() wait() end
The error "interval is empty" means that the lo
and hi
in math.random(lo, hi)
are such that lo > hi
.
In your case, that must mean that #players
is 0
. ie., your code should only try to work if there is enough players to play. If not, you should wait until there is.
:GetPlayers()
returns a list of the players playing at that time. Since you never update players
, it will just be the list of players playing when the script started -- i.e., no one.
You should be grabbing players right where you use it.
Instead of devoting a lot of code to getting two different players, just do something like this:
local players = game.Players:GetPlayers() if #players >= 2 then -- ONLY if there are enough players -- Select one player, then remove them from the list of available players: local one = table.remove(players, math.random(#players)) local two = table.remove(players, math.random(#players))
pairs
takes a list. If you want to do something for both, you could use something like pairs({one, two})
but it would make more sense to write a function instead using a loop for that.