To Return True, or Not To...

…THAT is the question. Before I get started, have you ever found yourself in any of the two undesired situations below (if you intended them to happen that way, then this article is not for you):

  1. You add a touch listener to two different objects, and at some point in your app, the two objects overlap. When you go to touch the object on top, the “began” phase fires on it, but then the object underneath also receives the touches.

  2. You have a ui.lua button that happens to be above another object or group that can also receive touch events, and the same situation above happens—only your button “sticks” and is rendered useless for the duration of your app’s runtime.

Do you want to know a quick, one second solution to BOTH of those problems? How’d I guess :–)

Solution to situation #1: In your touch event listener function, make sure that you are returning true (e.g. via a “return true” statement).

Solution to situation #2: In your event listener you specified for your UI button, ditto above.

And there you go, problem solved. This little tip has saved me lots of frustration, stress, time, and the list goes on.

And now for the explanation. When it comes to “touch” events, if the listener function returns true, then that indicates that your touch target was intended and stops there. If it returns false (or nil—in other words, you didn’t tell it to return anything), then the touch will pass through that object and enable touches behind it.

In that situation, if there’s something that has a touch listener assigned to it behind the object you intended to touch, then that object will also receive touch events. The unfortunate thing is, the first object you touched will only receive a “began” touch phase, and not an “ended” phase (which explains all the crazy behavior of ui buttons in this situation).

And there you have it, another life-saving tip for you to put in your “Corona/Lua Toolbox” for those late-night coding/tempted-to-rip-your-hair-out-of-your-head sessions.

And speaking of “late night” … I need to go to bed.

HostGator $3.96

$3.96 for web hosting – used by Get started today.