为什么你可以设置 __index 等于 table

why can you set __index equal to a table

索引元方法可以设置为等于表。据我所知

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

foo.__index = bar

都一样。为什么在这种情况下允许以这种方式声明函数?

这不是函数声明 - 将 table 分配给 __index 只是使用您描述的函数的快捷方式。

来自Programming in Lua(对于Lua 5.0,但这部分语言没有改变):

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.

它不像你分配的 table 神奇地变成了一个函数。 type(foo.__index) 仍然会 return table,你仍然可以用它做一些你可以用其他 table 做的事情,比如使用 pairs 和 [=14] =],等等