Just now, while working, I had occasion to use the much maligned ternary operator. Unfortunately I was working in python which doesn’t have the ternary operator per-se and so I had to call a friend (my ADSL was offline) and ask about the python idiom for such an operator. The option he gave me got me thinking about how lua lacks a ternary operator also and how you would implement it in Lua.

Language Ternary idiom
C `condition ? truth_result : falsehood_result`
Python `[ falsehood_result, truth_result ][ condition ]`
I was told that this is actually unpythonic and that I should use a function
Lua `( condition and truth_result ) or falsehood_result`
This only works if the `truth_result` is not a false value and so people commonly end up using a function here too

This set me to thinking again about how I’d rather like a Luaish ternary operator for my Aranha project. Unfortunately so far all I have come up with would not work due to Lua’s slightly odd statement separation. I will either have to introduce a new lexeme or else find some way to re-use lua’s lexemes in an effective way without compromising the statement parser.

Possible structures I came up with include truth_result if condition else falsehood_result but that suffers from using if in an awkward position for statement separation. I was also considering (condition then truth_value else falsehood_value) explicitly parenthesised. Unfortunately that adds unusual messes into the expression parser.

I’m interested in what people think about the ternary operators in any case and if people have experience of using languages where ternary operators aren’t present per-se, I’d be interested in knowing what you’d recommend.

Comments on this page are closed.