Reputation: 12670
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. So I'll use code to explain myself and what I'm attempting.
I have a class I define by (simplified):
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.
Is there a pattern I can follow to achieve what I want?
Upvotes: 1
Views: 740
Reputation: 9490
Personally I would take "onEvent" out, like this:
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. Then the call is still 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
}
Upvotes: 4