lua-users home
lua-l archive

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


Hi!
 
Usually the order of operations in a Lua _expression_ is quite obvious for a human:
in "a+b*c" the multiplication is calculated first,
in "a|b&c" the calculation starts from bitwise AND.
But sometimes a Lua programmer might be confused by default precedence.
For example, I'm still making errors like "1<<k-1"
 
Obviously, it's a good idea to include extra parentheses to improve code readability.
I want to ask your opinion about when redundant parentheses are useful and when they are not.
 
The following matrix shows my guess of when parentheses should be used.
 
There are 12 types of operators listed in the "Precedence" section of the Lua manual.
Row = the type of operator being calculated first,
Column = the type of operator being calculated second.
 
1st\2nd|  or  and   ==   |    ~    &    <<   ..   +    *  unary  ^
-------+-----------------------------------------------------------
   or  | ---  ( )  ( )  ( )  ( )  ( )  ( )  ( )  ( )  ( )  ( )  ( )
  and  | ---  ---  ( )  ( )  ( )  ( )  ( )  ( )  ( )  ( )  ( )  ( )
   ==  | ---  ---  YES  ( )  ( )  ( )  ( )  ( )  ( )  ( )  ( )  ( )
   |   | ---  ---  ---  ---  ( )  ( )  ( )  ( )  ( )  ( )  ( )  ( )
   ~   | ---  ---  ---  YES  ---  ( )  ( )  ( )  ( )  ( )  ( )  ( )
   &   | ---  ---  ---  ---  ---  ---  ( )  ( )  ( )  ( )  ( )  ( )
   <<  | ---  ---  ---  ---  ---  ---  YES  ( )  ( )  ( )  ( )  ( )
   ..  | ---  ---  ---  YES  YES  YES  YES  ---  ( )  ( )  ( )  ( )
   +   | ---  ---  ---  YES  YES  YES  YES  YES  ---  ( )  ( )  ( )
   *   | ---  ---  ---  YES  YES  YES  YES  YES  ---  ---  ( )  ( )
 unary | ---  ---  ---  YES  YES  YES  YES  YES  ---  ---  ---  ( )
   ^   | ---  ---  ---  YES  YES  YES  YES  YES  ---  ---  ---  YES
 
"---" = parentheses are not needed, the correct order of operations is obvious for any Lua programmer
"YES" = it's recommended to use syntactically redundant parentheses to avoid possible confusion
"( )" = the parentheses are mandatory due to the first operation has lesser priority than the second one
 
For example,
for "(1<<k)-1" the row is "<<" and the column is "+", the cell is "( )".
for "1<<(k-1)" the row is "+" and the column is "<<", the cell is "YES".
for "(a and b) or c" the row is "and", the column is "or", the cell is "---".
 
What would you change in the matrix according to your favorite coding style?