Why can you set __index equal to the table

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

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

      

and

foo.__index = bar

      

match. Why are such functions allowed in this situation?

+3


source to share


1 answer


This is not a function declaration. The purpose of the table __index

is just a shortcut to using the described function.

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



The use of __index metadata for inheritance is so common that Lua provides a shortcut. Despite the name, the __index metadata does not need to be a function: it can be a table instead. When it's a function, Lua calls it a table and the missing key as arguments. When it's a table, Lua overrides the access on that table.

It doesn't look like the table you are magically assigning is becoming a function. type(foo.__index)

It will continue to recover table

, and you can do with it what you can do with other tables, for example, by using pairs

and next

etc.

+2


source







All Articles