Order of operators on subtract

37 Views Asked by At
print(table.getn(szExtension_Locations) - (g_nNumTeleportEntries - 1));
print(table.getn(szExtension_Locations) - g_nNumTeleportEntries - 1);

Output:

125
123

Why do these two lines of code produce a different result? Nothing is happening to the variables in between. The code is in that exact order. Even if I swap them, they still produce 123 then 125.

1

There are 1 best solutions below

3
werner On

The explanation are your parentheses: Your first expression evaluates to:

a - (b - 1) = a - b + 1

while your second expression evaluates to:

a - b - 1

Thus you see the difference of 2.

This calculation is completely unrelated to Lua:

Operator precedence works the same way in Lua as it typically does in mathematics. [...] Parentheses can be used to arbitrarily change the order in which operations should be executed.

More details about the minus sign before the parentheses can be found here.