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

How do I pick a random player from a table?

I am trying to make it so it picks a random player from the players table. It isn't working. Here is my code:

local plrs = {}
for _, v in pairs (game.Players:GetChildren())do
	table.insert(plrs, v)
	print(v)
end

while true do
	wait()
	local chosenplr = plrs[math.random(1, #plrs)]
	print(chosenplr.Name)
	
end

Error: ServerScriptService.PlrTurnScript:9: invalid argument #2 to 'random' (interval is empty)

3 answers

local Players = game:GetService("Players") 

local function onCharacterAdded(character)
	while true do
		wait(5) --needs a wait else it crashes alse means the time when a new person gets chosen
	local plrs = game.Players:GetChildren()
	local n = math.random(0, #plrs)
	for i, v in pairs(plrs) do
		if i == n then if workspace:FindFirstChild(v.Name)then
				print(v.Name) -- for now its prints the chosen player name

			end
		end
		end
		end
end

local function onPlayerAdded(player) 
	player.CharacterAdded:Connect(onCharacterAdded) 
end 
Players.PlayerAdded:Connect(onPlayerAdded)

you can also just take these lines and paste them in ur own code, this will give an error at the start of the game because the player still has to load in

local plrs = game.Players:GetChildren()
local n = math.random(0, #plrs)
for i, v in pairs(plrs) do
	if i == n then if workspace:FindFirstChild(v.Name)then
			print(v.Name) -- for now its prints the chosen player name

		end
	end
	end

Pitched_mobile idea is a very good one for beginners and is not bad but what i really reccomend is

Lets say if you wanted to get something from a table you would have to get its position how do you do that?? Its simple.

local menu = {"Chicken","Hotdog","Burger"}
--[[
We want hotdog!
The hotdog is on the 2nd row of the table.
So we will index it like this
--]]
local choosenfood = menu[2]
print(choosenfood) --Prints hotdog!

So how you want to do this with a player is

local players = game.Players:GetPlayers()
local choosenplayer = players[math.random(0,#players) --im not sure if it should be 1 or 0 but it should probably be 0
print(choosenplayer.Name) --Will print the random player's name.

Let me know if this helps!

2 comments

0

ye that doesnt work

0

oh i forgot i rushed on it im sorry i will try it n studio sty here

try this:

local plrs = game:GetService("Players"):GetChildren()
for _, v in pairs (game.Players:GetChildren())do
    table.insert(plrs, v)
    print(v)
end

while true do
    wait()
    local chosenplr = plrs[math.random(1, #plrs)]
    print(chosenplr.Name)

end

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