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
Add a comment  | 

1 Answer 1

Reset to default 1

The 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