Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to check if something is already in a table?

Asked by
ItsMeKlc 235 Moderation Voter
8 years ago

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
0
Use another for loop to go through evey item in the table and check if it's the same as your new number GoldenPhysics 474 — 8y

1 answer

Log in to vote
0
Answered by
DevSean 270 Moderation Voter
8 years ago

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

0
Why not just put an else instead of another variable line 7? GoldenPhysics 474 — 8y
0
Because it's in a for loop, putting an else would place it into the table multiple times DevSean 270 — 8y
Ad

Answer this question