Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

get 2 random players?

i am trying to get 2 random players (playerA and playerB) but i get this error when i start test: ServerScriptService.main:16: bad argument #2 to 'random' (interval is empty)


local playerA = nil
local playerB = nil

local started = false




while wait() do
	wait(1)

	if not started then
		if playerA == nil then
			local players = game.Players:GetChildren()
			local randomplayer = players[math.random(1,#players)]
			if randomplayer == playerB then
				repeat
					local randomplayer = players[math.random(1,#players)]
				until randomplayer ~= playerB
				playerA = randomplayer
			else
				playerA = randomplayer
			end
			print(playerA)
		end
		if playerB == nil then
			local players = game.Players:GetChildren()
			local randomplayer = players[math.random(1,#players)]
			if randomplayer == playerA then
				repeat
					local randomplayer = players[math.random(1,#players)]
				until randomplayer ~= playerA
				playerB = randomplayer
			else
				playerB = randomplayer
			end
			print(playerB)
		end
	end
end

1 comment

0

This script is ridiculously complicated for something that just needs to pick two values.

1 answer

✓ Accepted answer

The error says "interval is empty". That means the max is smaller than the min. Since the min is 1 and the max is #players, that means you have 0 players.

You aren't making sure you have at least two players before you go ahead and pick them!

In any case, you can do this much more simply.

First: playerA and playerB should be local to the loop. There isn't a good reason to make them not local. Nothing will ever set them to nil, anyway.

That said, playerA doesn't depend on playerB, at all.

Third, you can take advantage of table.remove to completely eliminate all loops:

while wait() do
	local players -- use GetPlayers instead of GetChildren
	repeat
		wait()
		players = game.Players:GetPlayers()
		-- wait until there are at least two players
	until #players >= 2
	-- if you only give math.random one value, then it assumes the min is 1
	-- table.remove returns the thing removed while changing the list
	local playerA = table.remove(players, math.random(#players))
	local playerB = table.remove(players, math.random(#players))
	print(playerA, playerB)
end

This discussion is preserved as it was. New answers, comments, and votes are closed.