OO Lua addEventListener, event is nil

I have a problem using OO Lua, I think its just syntax, but i can’t find any solution so I am posting here.

The OO Lua form I am using is shown below. The button is created as part of the object, ‘initbuttons’ is called to add the event listeners, then when the button is touched the listener function is called but even is nil.

ERROR:
attempt to index local ‘event’ (a nil value)

[lua]mClass = {}
mClass.__index = mClass
object = {}

function mClass.new()
setmetatable(object,mClass)
object.button = display.newImage(…etc

return object
end

function mClass:buttonTouchListener(event)
–this function is called when button is touched, but event is nil
end

function mClass:initButtons()
– this function is called externally to add listener
self.button:addEventListener(“touch” , self.buttonTouchListener)
end[/lua]

any ideas or suggestions would be greatly appreciated. [import]uid: 141923 topic_id: 31565 reply_id: 331565[/import]

Try this. :slight_smile:

button.lua

Button = {}  
Button.\_\_index = Button  
  
function Button.new()  
 local instance = {}  
  
 setmetatable(instance,Button)  
  
 instance.button = display.newCircle(100,100,50)  
   
 return instance  
end  
   
function Button.buttonTouchListener(event)  
 print(event.phase)   
end  
   
function Button:init()  
 -- this function is called externally to add listener  
 self.button:addEventListener("touch" , self.buttonTouchListener)  
end  

main.lua

require "button"  
  
local btn = Button.new()  
  
btn:init()  

[import]uid: 21331 topic_id: 31565 reply_id: 126156[/import]

Thankyou I have updated my code, but now I can’t access ‘self’ within the listener, I have had to do a hack and create a global reference to self, which isn’t great but works for the moment.

Do you know if there is a better way to access self (as in the instance) from within the listener ? [import]uid: 141923 topic_id: 31565 reply_id: 126222[/import]

Try this. :slight_smile:

button.lua

Button = {}  
Button.\_\_index = Button  
  
function Button.new()  
 local instance = {}  
  
 setmetatable(instance,Button)  
  
 instance.button = display.newCircle(100,100,50)  
   
 return instance  
end  
   
function Button.buttonTouchListener(event)  
 print(event.phase)   
end  
   
function Button:init()  
 -- this function is called externally to add listener  
 self.button:addEventListener("touch" , self.buttonTouchListener)  
end  

main.lua

require "button"  
  
local btn = Button.new()  
  
btn:init()  

[import]uid: 21331 topic_id: 31565 reply_id: 126156[/import]

Thankyou I have updated my code, but now I can’t access ‘self’ within the listener, I have had to do a hack and create a global reference to self, which isn’t great but works for the moment.

Do you know if there is a better way to access self (as in the instance) from within the listener ? [import]uid: 141923 topic_id: 31565 reply_id: 126222[/import]