1

I'm trying to create a function that checks to see if an element is already in an array, but I'm having trouble passing a table to a colon function. The following code is giving me the error "attempt to call method 'inTable' (a nil value)":

function main()
    test = {1,2}

    if test:inTable(1) then
        print("working")
    else
        print("not working")
    end
end

--Checks to see if an element is in a table
function table:inTable(element)

    --Go through each element of the table
    for i in pairs(self) do
        --If the current element we are checking matches the search string, then the table contains the element
        if self[i] == element then
            return true
        end
   end

    --If we've gone through the whole list and haven't found a match, then the table does not contain the element
    return false
end

If I change this so that I call "inTable(test, 1)" instead of "test:inTable(1)" and change the function definition to "function inTable(self, element)" this works correctly. I'm not sure why using a colon function here isn't working.

2
  • 3
    possible duplicate of How do I add a method to the table type? Commented Jul 15, 2015 at 16:33
  • It also took me a while to understand the difference between "test:inTable(1)" and "table.inTable(test, 1)". I have documented my steps to analyze this difference here -- maybe it helps. Commented Oct 11, 2015 at 8:49

1 Answer 1

2

table is a namespace, not a metatable applied to all table instances.

In other words, you can't add methods to all tables like that. The closest you can get would be a function that you pass all your newly constructed tables through to add a metatable:

local TableMT = {}
TableMT.__index = TableMT
function TableMT:inTable(element)
    for i in pairs(self) do
        if self[i] == element then
            return true
        end
   end
   return false
end
function Table(t)
    return setmetatable(t or {}, TableMT)
end

function main()
    test = Table {1,2}

    if test:inTable(1) then
        print("working")
    else
        print("not working")
    end
end
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.