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

How to select several random players?

Hello! So I'm trying to make a system that randomly chooses several players to be inserted into a table. Say I want to put 10 players into a table randomly, how do I do that? (It can't select the same player twice)

I've tried to do this:

local Players = game:GetService("Players")

local Murderers = {}
local Civilians = {}

function AssignTeams()
	local Player = Players:GetPlayers()
	
	repeat
		table.insert(Murderers, Players[math.random(1, #Players)])
		table.insert(Civilians, Players[math.random(1, #Players)])
	until #Murderers == 2 and #Civilians == 10
	
end

AssignTeams()

Even if it does works, I want to find a more efficient (if possible, more effective) way to do this. Cheers!

1 answer

✓ Accepted answer

Not sure if it is 'efficient' or 'effective'

local Players = game:GetService("Players")

local Murderers = {}
local Civilians = {}

function AssignTeams()
    local Player = Players:GetPlayers()
	local playersnotyetselected = {}
	for i, v in pairs(Player) do
		table.insert(playersnotyetselected,i,v)
		
	end

    repeat
	local plr = playersnotyetselected[math.random(1, #playersnotyetselected)]
        table.insert(Murderers,1, plr)
	table.remove(playersnotyetselected,table.find(playersnotyetselected,plr))
	
    until #Murderers == 2 
	for i, v in pairs(playersnotyetselected) do
		table.insert(Civilians, i,v)
	end
end

AssignTeams()

table.find returns the index if the obj is found but if not then nil

4 comments

0

I edited my answer. I just released I had to do the table,index,value on table.insert

0

Alright, thank you! I can finally sleep in peace.

0

:GetPlayers gives you table copy, you can modify that

0

@imKirda Oh, ok.

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