Duplicate checker function breaking?

Hello, I’m trying to create a system where you type


team1, team2 = chooseTeams(tableName)

and it returns 2 items randomly from a list but they can’t be the same (cant both return the same)

This is the function I’ve created:


function chooseTeams(tableToChoose)
	local team1 = table.Random(tableToChoose)
	local team2 = table.Random(tableToChoose)
	
	if team2 == team1 then
		chooseTeams(tableToChoose)
	end
	
	return team1, team2
end

But I tested it by printing the 2 variables and most of the time I didn’t get dupes but I still have occurrences of team1 and team2 being the same

Anyone know why this may be happening?

[lua]
function chooseTeams(tableToChoose)
local team1 = table.Random(tableToChoose)
local team2 = table.Random(tableToChoose)

if team2 == team1 then
	return chooseTeams(tableToChoose)
end

return team1, team2

end
[/lua]

you forgot to make it recursive. However, with this kind of thing, you don’t want it to be recursive. Try this

[lua]
function chooseTeams(tableToChoose)

-- Don't know if modifying the table is safe so copy
local tableCopy = table.Copy(tableToChoose)

local team1, key1 = table.Random(tableCopy)
table.remove( tableCopy, key1 )
local team2 = table.Random(tableCopy)

return team1, team2

end
[/lua]

Adding the


return

fixed it and it works great!

I tried your other way that you put at the bottom and got this error:


[ERROR]sh_chooseteams.lua:6: bad argument #1 to 'remove' (table expected, got string)

On a side note how do you mark someone’s post as “Agree” or “Friendly” or whatever? I don’t have any buttons on my screen i see for that