在构造函数参数中使用Lua成员函数

由于我刚学Lua,而它不像我习惯的面向对象编程,所以标题中可能使用的不是正确的单词。因此,我将使用代码来解释自己的意思和尝试的内容。

我有一个类的定义(简化):

function newButton(params)
  local button, text
  function button:setText(newtext) ... end
  return button
end

我正在尝试创建一个按钮,当单击时它的文本将发生更改。所以我按以下方式创建它(简化):

local sound = false
local soundButton = Button.newButton{
  text = "Sound off",
  onEvent = function(event)
    if sound then
      sound = false; setText("Sound on")
    else
      sound = true; setText("Sound off")
    end
  end
}

这都很好,它可以工作,但是它告诉我无法调用setTextattempt to call global 'setText' <a nil value>。我尝试使用soundButton:setText(""),但也不起作用。

有没有模式可以遵循以实现我想要的功能?

原文链接 https://stackoverflow.com/questions/7085720

点赞
stackoverflow用户111886
stackoverflow用户111886

个人意见是将"onEvent"移除,如下:

function soundButton:onEvent(event)
  if sound then
    sound = false
    self:setText("Sound on")
  else
    sound = true
    self:setText("Sound off")
  end
end

但如果你真的想保留它,那么"onEvent"必须被声明为一个需要两个参数的函数,即(显式的)self参数和事件。然后调用仍然是self:setText

例如:

local soundButton = Button.newButton{
  text = "Sound off",
  onEvent = function(self, event)
    if sound then
      sound = false; self:setText("Sound on")
    else
      sound = true; self:setText("Sound off")
    end
  end
}
2011-08-16 23:05:33