admin管理员组文章数量:1125950
I'm trying to create a hierarchical UI in Lua. The following code is called with local ui = UI:new()
and then local w = ui.addWidget()
. But the child Widget doesn't inherit the __tostring
metamethod of the parent "class" (UI). Printing it outputs the default string ("table 0x...").
What am I doing wrong here?
function UI:new()
local o = {
type = 'UI',
x = 0,
y = 0,
widgets = {}
}
o.root = o
setmetatable(o, self)
self.__index = self
self.__tostring = function()
return 'whatever'
end
return o
end
function UI:addWidget(widget)
local w = widget or UI.Widget:new()
w.root = self.root
table.insert(self.widgets, w)
return w
end
UI.Widget = {}
setmetatable(UI.Widget, {__index = UI })
function UI.Widget:new()
local o = {
type = 'UI.Widget',
root = self,
isEnabled = true,
--- more fields...
}
setmetatable(o, self)
self.__index = self
return o
end
```
I'm trying to create a hierarchical UI in Lua. The following code is called with local ui = UI:new()
and then local w = ui.addWidget()
. But the child Widget doesn't inherit the __tostring
metamethod of the parent "class" (UI). Printing it outputs the default string ("table 0x...").
What am I doing wrong here?
function UI:new()
local o = {
type = 'UI',
x = 0,
y = 0,
widgets = {}
}
o.root = o
setmetatable(o, self)
self.__index = self
self.__tostring = function()
return 'whatever'
end
return o
end
function UI:addWidget(widget)
local w = widget or UI.Widget:new()
w.root = self.root
table.insert(self.widgets, w)
return w
end
UI.Widget = {}
setmetatable(UI.Widget, {__index = UI })
function UI.Widget:new()
local o = {
type = 'UI.Widget',
root = self,
isEnabled = true,
--- more fields...
}
setmetatable(o, self)
self.__index = self
return o
end
```
Share
Improve this question
asked 17 hours ago
CirrocumulusCirrocumulus
6105 silver badges20 bronze badges
1 Answer
Reset to default 1The manual states:
Lua queries metamethods in metatables using a raw access (see rawget).
Therefore, you cannot expect to use __index
to inherit metamethods, you must define the metamethods explicitly.
UI.Widget = {
__tostring = function ()
return 'widget'
end
}
本文标签: oopHow to inherit both methods and metamethods in LuaStack Overflow
版权声明:本文标题:oop - How to inherit both methods and metamethods in Lua - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736572934a1944794.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论