Object Lua设置元表中的索引
我尝试在Lua中执行基本继承,但我不太明白为什么在调用Object Lua设置元表中的索引,object,lua,Object,Lua,我尝试在Lua中执行基本继承,但我不太明白为什么在调用print()时,下面的代码没有索引表mt.prototype 它说,mt.prototype不存在,但我不明白为什么。当您重新分配给它时,您正在覆盖第9行的mt。这将破坏prototype字段 如果这是你第一次尝试这种东西,不要把事情复杂化。您的\uuu index函数将执行与让\uu index=tbl处理相同的操作 local main_table = {} local proto_table = { value = 5 }
print()
时,下面的代码没有索引表mt.prototype
它说,
mt.prototype
不存在,但我不明白为什么。当您重新分配给它时,您正在覆盖第9行的mt
。这将破坏prototype
字段
如果这是你第一次尝试这种东西,不要把事情复杂化。您的\uuu index
函数将执行与让\uu index=tbl
处理相同的操作
local main_table = {}
local proto_table = {
value = 5
}
setmetatable(main_table, { __index = proto_table })
print(main_table.value)
如果您想要稍微复杂一点的设置,请研究以下内容:
local main_table = {}
local meta_table = {
prototype = {
value = 5
}
}
meta_table.__index = meta_table.prototype
setmetatable(main_table, meta_table)
print(main_table.value)
请注意,在RHS评估期间,分配的LHS没有完全量化,这就是为什么必须在单独的行上设置\u索引的原因
local main_table = {}
local meta_table = {
prototype = {
value = 5
}
}
meta_table.__index = meta_table.prototype
setmetatable(main_table, meta_table)
print(main_table.value)