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

How to check if something is already in a table?

I want this script to only add a number to this table if its not there. How can I ensure that it wont add a number if it's only there?

numbers = {}
for i=1,10 do
	local N = math.random(1,10) 
	table.insert(N)
end

1 comment

0

Use another for loop to go through evey item in the table and check if it's the same as your new number

1 answer

✓ Accepted answer

You have to loop through the table and check if the value you are inserting is already in it, for example:

numbers = {}
for i=1,10 do
	local N = math.random(1,10) 
	local alreadyExists = false
	for _, number in pairs(numbers) do -- loop through the array
		if (N == number) then 		-- check the array value against the new number
			alreadyExists = true	-- set the variable alreadyExists to true
			break
		end
	end
	if (not alreadyExists) then		-- if it's not in the array already
		table.insert(N)				-- insert it
	end
end

2 comments

0

Why not just put an else instead of another variable line 7?

0

Because it's in a for loop, putting an else would place it into the table multiple times

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