Why can you set __index equal to the table
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.
source to share