Take the 2-minute tour ×

I'd like to create a custom contains method on Lua's table data structure that would check for the existence of a key. Usage would look something like this:

mytable  = {}
table.insert(mytable, 'key1')


share|improve this question

1 Answer 1

up vote 3 down vote accepted

In Lua you cannot change ALL tables at once. You can do this with simpler types, like numbers, strings, functions, where you can modify their metatable and add a method to all strings, all functions, etc. This is already done in Lua 5.1 for strings, this is why you can do this:

local s = "<Hello world!>"
print(s:sub(2, -2)) -- Hello world!

Tables and userdata have metatables for each instance. If you want to create a table with a custom method already present, a simple table constructor will not do. However, using Lua's syntax sugar, you can do something like this:

local mytable = T{}

In order to achieve this, you have to write the following prior to using T:

local table_meta = { __index = table }
function T(t)
    -- returns the table passed as parameter or a new table
    -- with custom metatable already set to resolve methods in `table` 
    return setmetatable(t or {}, table_meta)

function table.findvalue(tab, val)
    for k,v in pairs(tab) do
        -- this will return the key under which the value is stored
        -- which can be used as a boolean expression to determine if
        -- the value is contained in the table
        if v == val then return k end
    -- implicit return nil here, nothing is found

local t = T{key1='hello', key2='world'}
print(t:findvalue('world'), t:findvalue('bar'), t:findvalue('xxx'))
if not t:findvalue('xxx') then
    print('xxx is not there!')

--> key2    2
--> xxx is not there!
share|improve this answer

Your Answer


