Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

get 2 random players?

Asked by
Kryddan 261 Moderation Voter
9 years ago

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
0
This script is ridiculously complicated for something that just needs to pick two values. BlueTaslem 18071 — 9y

1 answer

Log in to vote
4
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

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
Ad

Answer this question