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.

Jigsaw
  • 405
  • 5
  • 11
  • 3
    possible duplicate of [How do I add a method to the table type?](http://stackoverflow.com/questions/10778812/how-do-i-add-a-method-to-the-table-type) – Siguza Jul 15 '15 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](http://stackoverflow.com/a/33055312/1804173) -- maybe it helps. – bluenote10 Oct 11 '15 at 08:49

1 Answers1

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
Mud
  • 28,277
  • 11
  • 59
  • 92