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

How can I insert only two items into a table?

I want to insert two random players into a table, and check if they are in the table before they are put in, so that noone is put in the table twice. I have tried making this script, but I have no idea if it works.

if #contestants == 8 or #contestants == 9 or #contestants == 10 then
	for _, randomplayers in pairs(2 * math.random(1, #contestants)) do
		if randomplayers and randomplayers.Health > 0 then
			table.insert(robber, randomplayers)
		end
	end

Thanks!

2 comments

0

In your for loop you are trying to loop through a number?

0

It is supposed to pick a contestant. I figured out that the loopo above wasn't going to work.

2 answers

✓ Accepted answer

It is best to create a function to see if a value is in the table.

function InTable(tab,val)
	for _,n in pairs(tab) do
		if n == val then
			return true
		end
	end
end

if contestants == 8 or contestants == 9 or contestants == 10 then
	local RandomPlayer = contestants[math.random(1,#contestants)]
	if not InTable(robber,RandomPlayer) then
		table.insert(robber,RandomPlayer)
	end
end

1 comment

0

Thanks! But how can I put more than one contestant in the table? Say I only want have two players there, or even 4.

I believe I have solved it! If anyone else is wondering about the same thing, here is the script I made. Not sure if it works yet but I havee my fingers crossed (:

if #contestants == 8 or #contestants == 9 or #contestants == 10 then
	local randomplayer1 = contestants[math.random(1, #contestants)]
	while true do
		local randomplayer2 = contestants[math.random(1, #contestants)]
		if randomplayer2 ~= randomplayer1 then
			table.insert(robber, randomplayer1, randomplayer2)
			break
		end
	end

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