💾 Archived View for gemini.ctrl-c.club › ~jara25 › gemlog › 2023-08-23.gmi captured on 2024-08-18 at 17:29:17. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2023-09-08)

-=-=-=-=-=-=-

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