2011-08-16 4 views
1

저는 루아를 처음 접했기 때문에 제목에 맞는 단어를 사용하지 않을 것입니다. 따라서 코드를 사용하여 자신과 내가 시도하고있는 것을 설명 할 것입니다. 내가 한 번 클릭 텍스트의 변경하는 버튼을 만들려고 해요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 
} 

와 잘, 그것은 내가 soundButton:setText("")를 사용 해봤의 setText attempt to call global 'setText' <a nil value> 호출 할 수 있지만, 그 중 하나가 작동하지 않는 나에게 말한다 제외하고 작동 .
내가 원하는 것을 성취 할 수있는 패턴이 있습니까?

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

을하지만 당신이 정말로 그것을에서 유지하려는 경우, 다음의 onEvent는 두 개의 매개 변수를 함수의 (명시 적)로 선언해야합니다

답변

4

개인적으로 나는 다음과 같이 OUT "의 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 
}