Coroutine Repeating

What’s the goal?

I’m attempting to make it so that it when choosing a random player to matchmake with, if it lands on yourself; it will retry.

What’s the issue?

print(success,randomOpponent) returns true,JerimiahBatres which is my name, and then returns true,nil after that; erroring out other parts of the script.


Code
local opponentThread = coroutine.create(function()
		local randomOpponent = self["InQueue"][math.random(1,#self["InQueue"])]
		
		while true do
			coroutine.yield(randomOpponent)
		end
	end)
	
	local opponent = ""
	
	repeat
		local success,randomOpponent = coroutine.resume(opponentThread)
		opponent = randomOpponent
		print(success,randomOpponent)
	until randomOpponent ~= player
	
	self:teleportToGame(player,opponent)

Thanks for any help in advanced! :grinning_face_with_smiling_eyes:

local function GetRandomPlayer(tabl)
	if #tabl <= 1 then return end
	local RandIndex = math.random(1, #tabl)
	local RandomPlayer = tabl[RandIndex]
	if RandomPlayer == player then
		wait()
		table.remove(tabl, RandIndex) -- maybe?
		return GetRandomPlayer(tabl)
	else
		return RandomPlayer
	end
end

you could try this, I am assuming you have player defined already

function GetPlayer()
    local Table = game.Players:GetPlayers()
    table.remove(Table, table.find(Table, player))
    return Table[Random.new():NextNumber(1, #Table)]
end

I need the player to stay inside the queue table, the main thing is just making the function repeat if it lands on yourself.

Is this the full code of the script? If not, could you provide one that includes table with key ["InQueue"]?

Here’s the full code; I used fake players for testing purposes

Solved

local opponentThread = coroutine.create(function()
		while true do
            local randomOpponent = self["InQueue"][math.random(1,#self["InQueue"])]
			coroutine.yield(randomOpponent)
		end
	end)

Try nesting rannndomOpponent inside while do iteration, so ranndomOpponent can be refreshed per resumption.