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 get two random values from a table?

PlayersInServer={}
math.randomseed(tick())
			for i=1,2 do
				local value=math.random(1,#PlayersInServer)
				local picked=PlayersInServer[value]
			 	print(picked)
			end

This will usually just pick two of the same people, how would I get two random values?

1 comment

1

Make another table and put the first person in that table. Then check if the second value is the same person, and if it is then end the loop.

2 answers

local PlayersInServer = {}
local ChosenPlayers = {}
for i=1,2 do
	if i == 1 then
	local RandomValue = math.random(1,#PlayersInServer)
	local ChosenPlayer = PlayersInServer[RandomValue]
	table.insert(ChosenPlayers,ChosenPlayer)
	end
	if i == 2 then
		local RandomValue = math.random(1,#PlayersInServer-1)
		local PlayersInServerCopy = PlayersInServer
		table.remove(PlayersInServerCopy,ChosenPlayers[1])
		local ChosenPlayer = PlayersInServerCopy[RandomValue]
		table.insert(ChosenPlayers,ChosenPlayer)
	end
		
	RandomValue = math.random(1,#PlayersInServer)
end
for i=1,2 do
	print(ChosenPlayers[i])
end

This should work as a script for what you are doing. So on lines 5 to 7, it will generate a random value, choose a player then add it to the ChosenPlayers table. On lines 10 to 14, the script will generate a random value for the PlayersInServer table, minus one (because we have already used it in the ChosenPlayers table), it will then make a duplicate of PlayersInServer named PlayersInServerCopy, remove the already chosen value from PlayersInServerCopy and add the make a new ChosenPlayer and add it.

Something that may seem a little more simple. Note that this method is not ideal, as it will only works for finding two random players. Otherwise you'd want to use a Table to accomplish this.

local PlayersInServer = {}
math.randomseed(tick())

local previous;

for i=1,2 do
	repeat
		local value =math.random(1,#PlayersInServer)
	    	picked = PlayersInServer[value]
	until previous ~= picked
		
	previous = picked
    print(picked)
end

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