lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Quoth Martin Voigt <voigt.m@googlemail.com>, on 2010-09-14 18:47:11 +0200:
> Maybe I'm missing something. What's wrong with using a function for
> the ternary use case?
> 
> local value = ternary(condition, value_if_true, value_if_false)
> 
> Most problems that would require additional syntax in other languages
> can be solved using Lua's features in a way that the code stays
> straight forward and elegant. For me the addition of a ternary
> operator would mean I can replace the above code with
> 
> local value = condition ? value_if_true : value_if_false

  value = if a_is_valid then do_something_with(a) else some_default end
  -->
  value = hypothetical_expr_if(a_is_valid, do_something_with(a), some_default)

Evaluation order is bogotified; do_something_with(a) always 'happens'.

  value = if a_is_valid then do_something_with(a) else some_default end
  -->
  value = (a_is_valid and do_something_with(a)) or some_default

Subtle semantic problems depending on the result of
do_something_with(a).

Note that (IMHO) subtle semantic problems are the worst kind.  I was
rightfully chastised in my youth for using the (a and b) or c form at
one time when fiddling with Perl.  It's an invitation to error because
it looks like it works most of the time right up until it doesn't,
like a pipe that breaks when the water temperature is exactly 30 °C,
or a mathematical proof that has one missing conjoined antecedent.
One of the main reasons I like Lua is a widespread _absence_ of subtle
semantic gotchas, something that (e.g.) PHP, C++, and Perl can have in
spades (depending on how they're used).

The primary currently-valid plain-Lua form of the above that works
correctly is:

  -- (declaration if necessary) local value;
  if a_is_valid then
    value = do_something_with(a)
  else
    value = some_default
  end

with possible reformatting.  However, this can require the creation of
extra temporaries instead of being able to embed the whole thing into
an argument in a function call, for instance.  The target name(s) are
also duplicated, which could lead to other errors during maintenance.
So it works and is semantically clean but doesn't compose well.

I don't consider either of the other two choices above anything that I
would write today in place of a real conditional expression operator
except for using the and/or form in throwaway interactive evaluation
where speed of writing is essential.

   ---> Drake Wilson