The precedence of the not operator in Python and Lua

In a nutshell, there is a difference.

Consider the following code, which is valid in both Python and Lua:

print((not 1 == 2) == (not (1 == 2)))

This prints "True" in Python, but it prints "false" in Lua. The reason is that in Python, the comparison operators take precedence over the not operator, but in Lua, the not operator acts like a unary operator and has precedence over many operators, including the boolean operators.

Thus, the following code:

print((not 1 == 2) == ((not 1) == 2))

...prints "true" in Lua, but it prints "False" in Python.

I wrote this as a reminder to myself because a few days ago, I spent twenty minutes looking for a bug related to this. The easiest way to prevent bugs related to precedence is to use parentheses in order to make the intent clear, as few people want to memorize the precedence chart of any programming language.

External links

=> Operator precedence in Python | Operator precedence in Lua

=> Index

Proxy Information
Original URL
gemini://gemini.ctrl-c.club/~jara25/gemlog/2023-08-23.gmi
Status Code
Success (20)
Meta
text/gemini
Capsule Response Time
434.52029 milliseconds
Gemini-to-HTML Time
1.095702 milliseconds

This content has been proxied by September (ba2dc).