Reputation: 449
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.
Upvotes: 1
Views: 318
Reputation: 28991
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
Upvotes: 2