2011-08-16 248 views
1

我可能没有在标题中使用正确的单词,因为我是lua的新手,并不像我习惯的OO。所以我会用代码来解释我自己和我正在尝试的。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 
} 

这是所有良好和不好,它的工作原理除了它告诉我,我不能叫的setText attempt to call global 'setText' <a nil value>我一直在使用soundButton:setText("")尝试,但,不能正常工作。
有没有一种模式可以实现我想要的效果?

回答

4

个人而言,我将采取“的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: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 
}