2011-08-16 13 views
1

私はおそらくタイトルに正しい単語を使用していません。なぜなら私はluaを初めて使っているからです。だから私は自分自身と私が試みていることを説明するためにコードを使用します。私はそれを一度クリックしたテキストです変わるボタンを作成しようとしているluaコンストラクタパラメータのメンバ関数を使用

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

は、私は(簡体字)で定義したクラスを持っています。次のようにだから私は(簡体字)、それを作成します。

すべて良好であり、それは私が soundButton:setText("")を使用してみましたが、それはどちらか動作しないのsetText attempt to call global 'setText' <a nil value>を呼び出すことはできません私に指示を除いても、それが動作
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 
} 


私が望むことを達成するためのパターンはありますか?

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

をしかし、あなたが本当にそれを維持したい場合は、その後のonEventは、2つのパラメータをとる関数、(明示的)として宣言する必要があります。

答えて

4

個人的に私はこのように、アウト「の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 
} 
関連する問題