Corona Quick Tip – the ternary operator re boolean parameter defaults

I saw this being discussed in Corona Geek Episode 115 and thought I’d add my two cents..

The issue comes about when passing boolean values as optional arguments to a function, and how to efficiently test if nil and provide a default value. The common pattern for defaulting other types of values is:

This is a shortcut test for nil, using the fact that nil evaluates to false in logical statements, so the expression after “or” is returned instead.

However, if you’re passing a boolean value, this test is insufficient, because a legitimately supplied “false” value will always fail that test (and thus always return the default instead).

The “flaw” is in the binary logical test – as it’s essentially testing the wrong thing. It shouldn’t be testing for an implied false, it should be testing for an explicit nil. What would be handy is a ternary operator, to directly test for nil, then selecting either the passed value or the default. Some languages like C/C++ have a true ternary operator. Lua does not, though something nearly equivalent can be crafted from slightly more complex logical expressions:

The parenthesis surrounding the nil test are optional, but I added them to more closely imply the general form of the ternary pattern: a and b or c
But it’s not a “true” ternary operator, and there are some “gotchas”, particularly if “b” evaluates to false. That’s why foo() and bar() above are not identical – the logic must be reversed if your default value is intended to be false.

But with a bit of “practice” to keep the logic straight, defaulting booleans can again become a simple “one-liner”.

For further info, see the Lua Wiki entry on this topic.