Lua继承覆盖函数。

我对Lua比较新,正在尝试使用一个类系统。我想做的是有一个基类,它有许多属性,然后扩展这个类用于诸如按钮、文本框等对象。

基类将具有属性,例如 xywidthheight 等,其他类将具有 labelcolour 等类似属性。

如果我在基类上创建一个名为 render() 的函数,然后尝试稍后覆盖此函数,似乎不起作用。(可能我完全错误地使用了类!)

这是我使用的示例代码:

Base = {}
Base.__index = Base
function Base.create(value)
    local b = {}
    setmetatable(b, Base)
    b.value = value
    return b
end

function Base:render()
    print("I'm the base! : "..self.value)
end

Button = {}
Button.__index = Base

function Button.create(value)
    local b = Base.create(value)
    setmetatable(b, Button)
    return b
end

function Button:render()
    print("I'm a button! : "..self.value)
end

Button.create("TestBtn"):render()

我想让 Button.create("TestBtn"):render() 打印出 I'm a button! : TestBtn,但它打印了 I'm the base!:TestBtn

请问有人能帮我用新的函数覆盖原来的 render 函数吗?

谢谢,威尔。

点赞
用户107090
用户107090

使用 Button:render 代替 Button:test 进行定义。

2014-10-21 11:48:33
用户258523
用户258523

缺少的细节,正如@siffiejoe所提到的并且我所暗示的,就是你的 Button 对象不知道在 Button 表中查找方法。

我的解决方案是创建无用的表格来创建关联,因此并不是最好的解决方案,但说明了这一点。

@siffiejoe的答案更好,因为它更准确地编写了所需的功能和关系。然后还需要额外的步骤来链接“类”表(即setmetatable(Button, Base))。

关键是 index 元方法的操作。在lua 参考手册中有相关代码:

"index":访问表键值。

function gettable_event(table,key)
   local h
   if type(table)== "table" then
     local v = rawget(table,key)
     if v ~ = nil then return v end
     h = metatable(table).__ index
     if h == nil then return nil end
   else
     h = metatable(table).__ index
     if h == nil then
       error (...)
     end
   end
   if type(h)== "function" then
     return(h(table,key))- 调用处理程序
   else return h [key] - 或者对它进行重复操作
   end
end
2014-10-21 14:25:01