Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check in Lua if there are multiple elements in a table?

I made a program, which checks if in table has (for example) "A" and a "B" in itself. But it doesn’t works.

Here’s code:

function inTable(t,e)
    return t[e] ~= nil
end

--Example
local table_ = {"A","B"}

if inTable(table_,"A") and inTable(table_,"B") then
    --Do some stuff
end

Please, help me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried everything but it still doesn’t work.

>Solution :

You are checking if those exist as keys. You should be checking if they exist as values. You can change the function to this

function inTable(t,e)
    for k,v in pairs(t) do
        if v == e then
            return true
        end
    end
    return false
end

Also, in case you didn’t know

local table_ = {"A","B"}

is equivalent to

local table_ = {[1] = "A", [2] = "B"}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading