2011-08-16 250 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 
}