-- Leo's gemini proxy

-- Connecting to gemini.ctrl-c.club:1965...

-- Connected

-- Sending request

-- Meta line: 20 text/gemini

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

-- Response ended

-- Page fetched on Sun May 19 07:00:53 2024