Hacker News new | ask | show | jobs
by Heliodex 4 hours ago
A comment <https://github.com/LuaJIT/LuaJIT/issues/1475#issuecomment-47...> has already been made on the issue regarding the ternary operator, recommending `if x then y else z` over `x ? y : z`. This is exactly how it's done with if-then-else expressions in Luau <https://luau.org/syntax/#if-then-else-expressions>, another language compatible with Lua, and makes it a ton easier to nest (especially with elseif) and I believe still easier to read than `y if x else z`.
1 comments

The ternary operator is easy to nest if you put each clause on a separate line. Then it looks just like nested if-then-else.
I love the ternary operator as much as anyone. But dang if it doesn't get hard to read when there is are a few, nested even.

Does that operator compile to faster assembly that if I make the same logic with verbose `if` logic? Is that a language specific outcome?

    cond1 ? res1 :
    cond2 ? res2 :
    cond3 ? res3 :
    or_else_res
If they are truly nested, then that is confusing. But if you have an if-else chain, then it can be quite readable.
I find that so much harder to read compared to if/else or case/when in ruby.

The ? is basically an attempt to use fewer if/else, at the cost of condensed if-else like structure. I always need to look at both parts after the ? whereas in a single if or elsif I don't. case/when in ruby is even better here e. g. regex check:

   def foo(i)
     case i
     when /^cat/
       handle_cats
     when /^dog/
       handle_dogs
(I ommitted the "end"s here to just focus on the conditional logic.)