← Back to context

Comment by wavemode

18 hours ago

I don't think if-expressions have to affect existing semantics. Basically, in the parser you would have two different kinds of AST nodes, one for when the `if` keyword is encountered in statement position and another for when it's encountered in expression position.

Right now, `if` in expression position is just a syntax error ("unexpected symbol")

Well, I believe there could be some complications with parsing related to the fact that Lua grammar doesn't really requires semicolons between the statements.

But other than that, yeah, detecting "if" in the expression position is pretty unambiguous. No idea why most languages went with "cond-expr ? then-expr : else-expr" bracketed syntax instead.

  • Surely the most likely explanation is familiary from C?

    But e.g. ml-family languages (like OCaml, F#, Haskell) and Rust just have the *if* expression that has a non-void value. If your language accepts expressions as statements (most do?), then I think that should just be compatible out of the box.

    • Yes, but why C had that syntax? Oh, right, because it didn't use if-then[-else]-end for the conditional statement, and reusing if(cond)[-else] with prohibited braces would be awkward.

      Oh, and Lua most famously does not accept expressions as statements. Which, now that I think of it, would actually evade most of the parsing complications.