Inconsistent squaring behavior

local X = -3

print(X ^ 2, -3 ^ 2) -- 9, -9

When squaring a negative number, if it’s a variable then it will act as -3 * -3, but if it’s hardcoded then it acts as `-(3^2)

A lot of my code uses magnitude checks like Magnitude = ((X ^ 2) + (Y ^ 2)) ^ 0.5, is this safe to do? Will this ever return an incorrect result (0) if I give it -3, 3 as the X and Y?

^ binds more tightly to its left hand side operator than - to its right hand side.

-a ^ b is actually -(a ^ b). If you want the correct behavior, you should write it as (-a) ^ b. This is by design in Lua.

8 Likes

For more information, this is called the “Operator Precedence” in a language, and Lua’s is as follows, with the top-most taking priority. In math you called it the order of operations or PEMDAS, but in programming the rules are expanded. It’s not listed, but parentheses are always first. Operators on the same line have the same precedence and are read left to right as they appear in your code.

^
not  - (unary)
*   /
+   -
..
<   >   <=  >=  ~=  ==
and
or
1 Like