Ludicrous Software

hasEventListener() in Corona

One of the nice things about Corona if you’re a Flash developer is the similarity between Corona’s API and some Flash APIs. For example, the event listener, although different in some respects, are also quite similar, which makes learning Corona a lot easier. But sometimes, those differences mean you’re missing out on things that you “take for granted” in Flash. For example, Corona has no native hasEventListener function. But I needed one, so I wrote one.

The hasEventListener function I wrote relies on the fact that there are some “hidden” properties in Corona that aren’t mentioned in the reference documents, but are completely accessible using plain old Lua. Specifically, objects that can listen for events will have a table storing the events being listened for and the functions to call when the events occur - you can get more background about this in an earlier post about the fastest way to remove all event listeners.

You can grab the code from the github repository I set up to hold all of the utility functions I use for Corona development. (I’ll be adding to it over time.)

Usage is pretty straightforward:

1
2
3
4
5
6
7
8
9
10
11
12
  -- import the module
  -- local Utilities = require("com.ludicroussoftware.Utilities")
  
  -- check for a function listener
  hasListener = Utilities.hasEventListener(object, "touch", onTouch)
  
  -- check for a table listener
  hasListener = Utilities.hasEventListener(object, "touch", object)
  
  -- check for any listener whatsoever
  hasListener = Utilities. hasEventListener(object, "touch")
  

A somewhat more detailed example is included in the repository.