What would be the correct way to verify if a value exists in the table in Lua?

Asked

Viewed 341 times

4

if not name in Namez do
    table.insert(Namez,name)
end

What would be the correct way to check if a name is not in the table?

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

2 answers

3

There’s nothing ready, you can create a function that does this, like this:

local function contains(tabela, valor)
    for i = 1, #tabela do
        if tabela[i] == valor then 
            return true
        end
    end
    return false
end

local names = {"joão", "maria", "josé"}
if not contains(names, "carlos") then
    table.insert(names, "carlos")
end
for i = 1, #names do
    print(names[i])
end

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

1

If you want to avoid having to do a linear search for the value, you can use the names as table key

if not Namez[name] then
    Namez[name] = true
end

You can iterate the table keys with the pairs function:

for name, _ in pairs(Namez) then
    -- ...
end

Note that the pairs function does not necessarily go through things in order. If the order of names is important, you can keep a list with table.Insert simultaneously to this mapping (you can even reuse the same table for the two, if the names are all strings).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.