Metatable 没有索引,即使使用了 setmetatable
Metatable is not indexed, even though setmetatable is used
根据 Lua 手册,setmetatable 仍然与 Lua 5.0 中的一样工作。然而出于某种原因,当我在 Lua 5.1.5 和 5.3.1 中尝试此代码时,似乎未访问元表:
ClassTable = {}
ClassTable.getString = function(self)
return self.x .. ""
end
inst = {}
setmetatable(inst, ClassTable)
inst.x = 7
--doens't work
assert(getmetatable(inst) == ClassTable)
print(inst:getString())
第一种情况有效,但在第二种情况下,我收到错误提示未使用元表:
./lua: /test.lua:12: attempt to call method 'getString' (a nil value)
stack traceback:
test.lua:12: in main chunk
[C]: ?
这也与方法调用运算符“:”无关,因为即使获取方法的值也不会进入元表。
print(inst.getString)
nil
要使 table inst
访问元 table 您需要使用元方法 __index
.
因此,您可以通过在 ClassTable.getString
定义下方的顶部添加此行来更正代码:
ClassTable.__index = ClassTable
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.
根据 Lua 手册,setmetatable 仍然与 Lua 5.0 中的一样工作。然而出于某种原因,当我在 Lua 5.1.5 和 5.3.1 中尝试此代码时,似乎未访问元表:
ClassTable = {}
ClassTable.getString = function(self)
return self.x .. ""
end
inst = {}
setmetatable(inst, ClassTable)
inst.x = 7
--doens't work
assert(getmetatable(inst) == ClassTable)
print(inst:getString())
第一种情况有效,但在第二种情况下,我收到错误提示未使用元表:
./lua: /test.lua:12: attempt to call method 'getString' (a nil value)
stack traceback:
test.lua:12: in main chunk
[C]: ?
这也与方法调用运算符“:”无关,因为即使获取方法的值也不会进入元表。
print(inst.getString)
nil
要使 table inst
访问元 table 您需要使用元方法 __index
.
因此,您可以通过在 ClassTable.getString
定义下方的顶部添加此行来更正代码:
ClassTable.__index = ClassTable
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.