问题描述
希望有人能理解我要弄清楚的事情,只是似乎对Lua的理解不足以实现这一目标.
Hope someone can make sense of what I'm attempting to figure out, Just don't seem to understand Lua enough to achieve this.
--[[
tbl.a.test("moo") returns "Table A moo appears"
tbl.b.test("moo") returns "moo appears"
]]
tbl = {
a = { ID = "Table A" },
b = {
test = function(...) print(... .. " appears") end,
},
}
tbl.a__index = function(self, ...) tbl.b[self](tbl.a.ID .. ...) end
我要尝试做的是可以创建几个表a,c,d,e,而不必将测试复制到每个表中.使用tbl.a.test
,tbl.c.test
,tbl.d.test
时,它将检索tbl.a.ID
变量,然后调用tbl.b.test(ID, "moo")
What I'm attempting to do is I could create several tables a, c, d, e and not have to copy test to each one. When tbl.a.test
, tbl.c.test
, tbl.d.test
is used, It'll retrieve the tbl.a.ID
var, then call tbl.b.test(ID, "moo")
到目前为止,我所能找到的只是在tbl.b之外的其他任何地方都找不到.test
So far all I'm finding out is it's not able to find .test on anything other than tbl.b
**编辑**到目前为止,感谢代码的支持;
** EDIT **Thank's to support so far the code is now;
tbl = {
a = { ID = "Table A " },
b = { test = function(...) local id, rest = ... print(id .. ": " .. rest) end },
}
setmetatable(tbl.a, {__index=function(self, k, ...) local rest = ... return tbl.b[k](tbl.a.ID, rest) end})
但是,由于某些奇怪的原因,...并未进展:|
However, the ... is not being progressed for some odd reason :|
推荐答案
- 您错过了
tbl.a
和__index
之间的时间段. -
__index
必须位于a
的元表上,而不是表本身. - 您没有从
__index
函数返回任何内容 -
self
是要建立索引的表,而不是键(这是第二个参数) - You're missing a period between
tbl.a
and__index
. __index
needs to be ona
's metatable, not the table itself.- You don't return anything from your
__index
function self
in the__index
function is the table being indexed, not the key (which is the second argument)
__index
函数中的这应该有效:
setmetatable(tbl.a, {__index=function(self, k) return tbl.b[k](tbl.a.ID) end})
这篇关于无法弄清lua表继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!