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

Randomly Choosing Two Players From a Table? [Gamescript timeout]

Sorry for reposting another question, how would I go upon selecting two random players from a table? I'd find that for my game, it'd be more efficient than choosing two players from a team, since I'd only be changing their teams from one to another. (Might not make sense, but just know I'd be using a lot of teams if I did the other method)

local teams = game:GetService("Teams")
local matchmaking = teams:WaitForChild("Matchmaking")

local round1 = matchmaking:WaitForChild("Round 1")
local round2 = matchmaking:WaitForChild("Round 2")
local round3 = matchmaking:WaitForChild("Round 3")

local PlayingTable = {}

for i, v in pairs(game.Players:GetPlayers()) do
	if v.Character then
		table.insert(PlayingTable, v.Name)
		local Players = game.Players:GetPlayers()
		local Chosen1 = PlayingTable[math.random(1, #PlayingTable)]
		local Chosen2 = PlayingTable[math.random(1, #PlayingTable)]
		repeat Chosen2 = PlayingTable[math.random(1, #PlayingTable)] until Chosen2 ~= Chosen1 --I'm getting a Gamescript timeout here
		print(Chosen1)
		print(Chosen2)
	end
end

Thanks,

LukeGabrieI

1 answer

✓ Accepted answer
local PlayingTable = {}

local pair1 = {}
local pair2 = {}

function getPair(table)
	if #PlayingTable >= 1 then 
		--inactive variables--
		local p1 = nil
		local p2 = nil

		--loop to get two different numbers--
		repeat wait()
			p1 = math.random(1, #PlayingTable)
			p2 = math.random(1, #PlayingTable)
		until p1 ~= p2

		--add players to pair1 table--
		table.insert(table, PlayingTable[p1])
		table.insert(table, PlayingTable[p2])
		
		--remove chosen players from playing table--
		--(to make sure if you fire getPair again it won't chose players from a pair table)
		table.remove(PlayingTable, PlayingTable[p1])
		table.remove(PlayingTable, PlayingTable[p2])

		--print names--
		if #table == 2 then 
			print(table[1].Name .. " vs " .. table[2].Name)
		end
	end
end

function cleanPair(table)
	if #table >= 1 then 
		for i = 1, #table do 
			table.remove(table, table[1])
			table.remove(table, table[2])
		end
	end
end

function choosePairs()
	getPair(pair1)
	getPair(pair2)
end

function cleanPairs() -- fire this function when the game ends
	cleanPair(pair1)
	cleanPair(pair2)
end

--fire function
choosePairs()

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