• Subject: Re: Ternary operator patch
• From: Mark Hamburg <mark@...>
• Date: Tue, 14 Sep 2010 09:22:32 -0700

```Another way to look at the issue of whether or not a ternary operator would be a good addition is to look at the code that it would be targeted at removing. What is the currently ugly/inefficient/error prone case that needs a cleaner alternative?

Perhaps the strongest argument is that the the work around for not having the operator -- "b and x or y" does not work if x is a false value. That's moderately compelling but what's the use case for this construct where it is much better than the imperative alternatives?

Compare this with the requests for a nil-friendly index operator:

a?.b?.c?.d

The use case here (and it's also one of the arguments for : message send sugar) is that the natural alternative to this in Lua is:

a ~= nil and a.b ~= nil and a.b.c ~= nil and a.b.c.d

But whereas the former does three table lookups, the latter does six and these can't necessarily be optimized out (short of tracing JIT techniques) because the index operation can invoke arbitrary code.

I'm not saying we need a nil-friendly index operator, but the case for it feels stronger than the case for a ternary operator.

Other ways to write the indexing case:

There's or-ing with an empty table. Unlike the above, this doesn't generate errors for attempting to index false (I guess we need the ternary operator for that). It's also a sea of nested parentheses:

local empty = { }
( ( ( a or empty ).b or empty ).c or empty ).d

There's the custom index function which somewhat conceals the meaning:

index( a, 'b', 'c', 'd' )

Or, if we disallow periods in keys:

index( a, 'b.c.d' )

If I'm going to advocate for extra operators, maybe what's needed is a pipe operator of some sort that feeds one expression into the next and avoids a certain number of parentheses:

a or nil | .b or nil | .c or nil | .d

That said, I've never thought about constructing something like this that would allow for index operations at the beginning of the pipe expressions. I've always thought about it more in terms of handing the results of the left-hand side to a function on the right-hand side.

But getting back to my core point, additional syntax is often easy but it accumulates rapidly and at some point it ceases to be easy. One wants to consider carefully the case that is being solved for and why the existing mechanisms are inadequate, inappropriate, excessively inconvenient, or excessively error prone. (This said as someone who floats syntax extension proposals fairly often.)

Mark

```