如何在Lua中将对象作为回调参数传递

时间:2018-01-17 11:09:38

标签: lua

定义一个View和ViewGroup类,View可以自定义的onDraw方法,遍历ViewGroup中的所有View对象,执行其onDraw方法,并将Canvas obj传递给{ {1}}方法。

无法在View的onDraw中调用Canvas的方法,也无法使用onDraw来调用View中的属性,可以保证Canvas obj是正确的。 示例代码如下:

self

错误提示:

ViewGroup = {    
  childcount = 0,
  childs = {} -- view object list
}

function ViewGroup:onDraw(canvas)
    for i=1,self.childcount do
          local childView = self.childs[i]
          childView:onDraw(canvas)
    end
end


View = {
    x = 0,
    y = 0,
    width = 0,
    height = 0,
    onDraw = nil
}

function View:new()
    local o = {
        onDraw = nil
    }
    setmetatable(o, self)
    self.__index = self
    return o
end

button1 = View:new()
button1.onDraw = function(canvas)
   -- the problem is here, can not call Canvas's method and can not call self.width
    canvas:save()
    canvas:fillRect(0, 0, self.width, self.height)
    canvas:restore()
end

1 个答案:

答案 0 :(得分:4)

您使用点(.)语法声明回调:

button1.onDraw = function(canvas)

但是你用冒号(:)来调用它:

childView:onDraw(canvas)

第二个调用约定意味着第一个传递的参数将是self,或者,在您的特定情况下,它等同于:

childView.onDraw(childView, canvas)

要解决此问题,请更改按钮的onDraw以使用:

function button1:onDraw(canvas)

或者手动添加self参数,就像Egor建议的那样:

button1.onDraw = function(self, canvas)