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
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
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
Why not just put an else instead of another variable line 7?
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.
1 comment
Use another for loop to go through evey item in the table and check if it's the same as your new number