Can't register a Runtime Event.

Hi guys, I’m having some problems with Runtime Events.

I need to detect when the back button of the device is pressed. After reading some posts in this forum ( https://forums.coronalabs.com/topic/70823-back-button-thoughts/ and https://forums.coronalabs.com/topic/65348-going-back-to-a-scene-with-android-back-button/)) I tried to register a global event for the back button as follows:

local myListener = function( event )     print( "Listener called with event of type " .. event.name )     if ( event.keyName == "back" ) then           print("BACK button pressed")     end     Runtime:removeEventListener( "key", myListener ) end Runtime:addEventListener( "key", myListener )

But when I test it on my device, I’m getting the following error:

I/Corona  (14160): ERROR: Runtime error

I/Corona  (14160): ?:0: attempt to index a nil value

I/Corona  (14160): stack traceback:

I/Corona  (14160):      ?: in function '?'

I/Corona  (14160):      ?: in function 'method’

I/Corona  (14160):      /Users/jenkins/slaveroot/workspace/Templates/label/android/platform/resources/init.lua:221: in function </Users/jenkins/slaveroot/workspace/Templates/label/android/platform/resources/init.lua:190>

If I’m reading it right, it seems I’m not able to access the Runtime object. I’ve tried this piece of code both in main.lua and in the scene where it should trigger it. Am I missing something?

Thanks in advance!

Hello,

it’s work for me.

Anyway, the myListener function is out of the scope for the removeEvent.

You need to write 

local myListener; myListener=function(event) ... end

or 

local function myListener(event) ... end

to grap the myListener function in the remove event.

Proof : 

local myListener = function( event ) <-- out of the scope for removing this event     print( "Listener called with event of type " … event.name )     if ( event.keyName == “back” ) then           print(“BACK button pressed”)     end print(myListener) <-- it’s nil ! Runtime:removeEventListener( “key”, myListener ) end Runtime:addEventListener( “key”, myListener )

Sincerely,

Yvan.

Hello,

it’s work for me.

Anyway, the myListener function is out of the scope for the removeEvent.

You need to write 

local myListener; myListener=function(event) ... end

or 

local function myListener(event) ... end

to grap the myListener function in the remove event.

Proof : 

local myListener = function( event ) <-- out of the scope for removing this event     print( "Listener called with event of type " … event.name )     if ( event.keyName == “back” ) then           print(“BACK button pressed”)     end print(myListener) <-- it’s nil ! Runtime:removeEventListener( “key”, myListener ) end Runtime:addEventListener( “key”, myListener )

Sincerely,

Yvan.