Search code examples
luametatablemeta-method

why can you set __index equal to a table


The index metamethod can be set equal to tables. From what I can tell

foo.__index = function(self, k)
    return bar[k]
end

and

foo.__index = bar

are the same. Why is declaring functions this way allowed in this situation?


Solution

  • This isn't a function declaration - assigning a table to __index is just a shortcut for using the function that you described.

    From Programming in Lua (for Lua 5.0, but this part of the language hasn't changed):

    The use of the __index metamethod for inheritance is so common that Lua provides a shortcut. Despite the name, the __index metamethod does not need to be a function: It can be a table, instead. When it is a function, Lua calls it with the table and the absent key as its arguments. When it is a table, Lua redoes the access in that table.

    It's not like the table that you assign magically becomes a function. type(foo.__index) will still return table, and you can still do things with it that you can do with other tables, like using pairs and next, etc.