Variables aren't holding negatives in math operations

I’m trying to work on some simple math and I ran into a problem when using negative variables

local x = -1
print(-0.05*x^2)
print(-0.05*-1^2)
print(x)

That will output

-0.05
0.05
-1

Why is it that when using the regular -1 it’ll properly output 0.05, but with the negative x variable it shows -0.05 instead, and how can I fix this?

This is because of the order that Lua does mathematical operations - it’s called precedence and you can read a bit about it here.

If you have a look at that page you can see that the exponential operation is executed before unary negation - that means your second operation (and anywhere else you stick a negative sign) is roughly equivalent to:

-0.05 * -1 * 1 ^ 2

And from PEDMAS you can see that the square term will be resolved first, and then the rest multiplied together to get a positive number.

The other operations give a negative as using a variable evaluates the unary operation first, making the equation equivalent to:

-0.05 * (-1 * 1) ^ 2

1 Like