简体   繁体   English

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

[英]lua using member functions in constructor parameters

I'm probably not using the right words in the title since I'm new to lua and it's not exactly OO like I'm used to.我可能没有在标题中使用正确的词,因为我是 lua 的新手,而且它不像我习惯的那样完全 OO。 So I'll use code to explain myself and what I'm attempting.所以我将使用代码来解释我自己以及我正在尝试什么。

I have a class I define by (simplified):我有一个 class 我定义为(简化):

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

I'm trying to create a button that will change it's text once clicked.我正在尝试创建一个按钮,一旦单击它就会改变它的文本。 So I create it as follows(simplified):所以我创建它如下(简化):

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
}

Which is all good and well, it works except it tells me I can't call setText attempt to call global 'setText' <a nil value> I've tried using soundButton:setText("") but that doesn't work either.这一切都很好,它可以工作,除了它告诉我我不能调用 setText attempt to call global 'setText' <a nil value>我试过使用soundButton:setText("")但这也不起作用.
Is there a pattern I can follow to achieve what I want?有没有我可以遵循的模式来实现我想要的?

Personally I would take "onEvent" out, like this:就我个人而言,我会删除“onEvent”,如下所示:

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

But if you really want to keep it in, then onEvent must be declared as a function that takes two parameters, the (explicit) self parameter, and the event.但是如果你真的想保留它,那么必须将 onEvent 声明为一个 function ,它接受两个参数,(显式)self 参数和 event。 Then the call is still self:setText .然后调用仍然是self:setText

For example:例如:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM