From the Lua 5.3 doc:
__index
: The indexing accesstable[key]
. ... The metamethod is looked up intable
.
It says the same thing for __newindex
, but not for any other metamethod.
If this were true (which it's not), it would be a major departure from previous versions of Lua. The following code outputs nil
, as I would expect, but it's inconsistent with the doc.
#!/usr/bin/env lua5.3
local proto = {a = 54}
local t0 = {__index = proto}
print(t0.a)
To be clear: If the doc was correct, I would expect t0
in the above code to only require an __index
field without an actual metatable for t0.a
to be 54
. So does anyone know what's going on with the doc?
You are incorrectly interpreting the meaning of the term. To say that it is "metamethod Y
is looked up in X" does not mean that it searches the X table for an entry named Y
. It means that it gets the metatable for X and looks up an entry named Y
, as if by rawget(getmetatable(X) or {}, "Y")
, as specified in the docs.
This terminology is repeatedly used in the metamethod descriptions. For example:
First, Lua will check the first operand (even if it is valid). If that operand does not define a metamethod for
__add
, then Lua will check the second operand.
It's not asking if the first (or second) operand have a method __add
; it asks if they have a metamethod __add
.
As you can see from the __add
example, you have to specify which of the operands it tries to get metamethods from, and in which order. For table[key]
, the point of the text is that doesn't try to get the metamethod from key
, only from table
. That may seem a tad bit obvious, but completeness is better than incompleteness.