why can you set __index equal to a table
Asked Answered
C

1

6

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?

Corriveau answered 2/6, 2017 at 4:0 Comment(1)
Have a look at the Lua string library for an example of when you would assign a table to __indexAdamantine
G
4

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.

Grandniece answered 2/6, 2017 at 4:46 Comment(2)
Using function does not allow list of bar fields when you have access to foo table.Sciolism
That's true, yes - I suppose that means that this feature isn't technically syntactic sugar. I'll tweak my answer a little. :)Grandniece

© 2022 - 2024 — McMap. All rights reserved.