[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Operator precedence and code readability
- From: Roberto Ierusalimschy <roberto@...>
- Date: Fri, 8 Jan 2021 15:40:01 -0300
> > Since this is probably a matter of opinion
> >
>
> Yes, it is opinion-based.
> And I want to know the mean opinion among Lua programmers.
My personal take is as follows. In general, I assume that the following
rules are well known and don't need parentheses:
- Arithmetic (bar exponentiation) and concatentation operations between
them.
- posfix > prefix > arithmetic/bitwise > comparisons > logical (and/or)
(Posfix operations among them have no ambiguity; idem for prefix.)
Everything else is more complex. Some specific cases:
- and vs. or: sometimes I would like to not use parentheses in this
case, but I am not sure how common is this knowledge among average
programmers.
- exponentiation: in Lua, it follows the usual mathematic rules, so
that -x^2 is equivalent to -x². Again, I am not sure how common
is this knowledge, so I am not always comfortable writing that
without parentheses. Idem for x^y^z (although that case is rare).
- bitwise operations: the rules for bitwise operations among them and
against arithmetic operations are far from obvious. Some could be
considered broken, due to the inheritance from C (where the rules for &,|
are "broken" for historical reasons). So, mostly anything in this case
are better written with parentheses.
- comparisons among them (e.g, a > b == (c < d)): comparisons probably
should be non associative, but that is difficult to implement when
the parser is based on precedence tables, as is the case in Lua.
Anyway, we should always use parentheses in those cases: (a > b) == (c < d).
When in doubt whether some expression is clear, it is better to err on
the side of extra parentheses.
-- Roberto