lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, 2011-01-04 at 11:48 +0100, Axel Kittenberger wrote:
> Can someone enlighten me on this bit.
> 
> > list_mt.__index = {
> >        insert = insert ;
> >        append = append ;
> >        remove = remove ;
> >        length = length ;
> >        unpack = unpack ;
> >        tostring = table.concat ;
> >        sort = table.sort ;
> > }
> 
> Why is __index a table and not a function? 

The __index can indeed be a table, it is a shortcut for a common
operation - looking up a value in another table. Quoting from PiL [1]:

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.

The same applies for __newindex. If __newindex is a table, not a
function, all assignments of nonexisting keys are directed into that
table.

[1] http://www.lua.org/pil/13.4.1.html