lua-users home
lua-l archive

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


On Fri, Jan 8, 2021 at 10:41 AM Roberto Ierusalimschy
<roberto@inf.puc-rio.br> wrote:
> - 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).

The knowledge may be there, but many (early) computer languages
(Fortran, Algol 68, Ada) did not have any right associative operators
outside of assignments, and unary operators had the highest priority.
Fortran, Algol68 and Ada interpret -x**2 as (-x)². Python uses the
same interpretation as Lua (for the ** operator). Languages with a C
style syntax (C, C++, Java, Go, C#) don't bother with an
exponentiation operator.

These are not the only things that can trip you up: the "not" operator
in Python has a low priority, just above "and", whereas the "not" in
Lua and the equivalent in most languages has the high priority of all
unary operators. "not a < b" is interpreted as "(not a) < b" by Lua,
and "not (a < b)" by Python. Fortran is similar to Python here.

I would suggest using parentheses when in doubt, because
mathematicians generally agree on the interpretation of expressions,
but programming language designers do not.

-- 
Gé