Reputation: 1872
Pardon me if the title doesn't make much sense. I had to choose between Is Lua's way of comparison usefull? and Comparison in Lua.
I wanted to do something like this today:
if currChar == nextChar == "-" then
...
end
but it kept returning false
everytime:
> currChar="-"
> nextChar="-"
> =currChar == nextChar == "-"
false
>
-- All true in Python
print(5 == 5) -- true
print(5 == 5 == 5) -- false
print((5 == 5) == (5 == 5)) -- true
print(5 == (4 + 1) == (6 - 1)) -- false
I fiddled with the values for some time and found out that for some reason, Lua compares values pairwise from left to right:
> = 52 > 3 > 2
stdin:1: attempt to compare number with boolean
stack traceback:
stdin:1: in main chunk
[C]: in ?
>
I's there a case when such a form of comparison is usefull?
Why do comparisons that way?
Upvotes: 2
Views: 598
Reputation: 4291
Lua's comparison operators are true binary operators. They work on two operands and that's it. In Lua, 5 == 5 == 5
is evaluated as (5 == 5) == 5
, which simplifies to True == 5
and is false. In Python, on the other hand, 5 == 5 == 5
is evaluated as 5 == 5 and 5 == 5
, which is true.
Python is atypical in supporting chaining of comparison operators, where x < y < z
is converted to x < y and y < z
. There aren't many languages of which I am aware that support that syntax.
As to whether or not it is useful, that's completely arbitrary. The chaining syntax is simply shorthand.
Upvotes: 5