2

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.

I tried everything but it still doesn't work.

1
  • Create table as local table_ = {["A"]=1,["B"]=1} and your code will work. Commented Oct 6, 2023 at 11:49

1 Answer 1

3

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"}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.