4

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?

Ace shinigami
  • 1,374
  • 2
  • 12
  • 25
  • Have a look at the Lua string library for an example of when you would assign a table to __index – Dafoosa Jun 02 '17 at 06:18

1 Answers1

2

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.

Jack Taylor
  • 5,588
  • 19
  • 35
  • Using function does not allow list of `bar` fields when you have access to `foo` table. – moteus Jun 02 '17 at 08:16
  • That's true, yes - I suppose that means that this feature isn't technically syntactic sugar. I'll tweak my answer a little. :) – Jack Taylor Jun 02 '17 at 08:48