1
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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
soulzek
  • 11
  • 4

1 Answers1

1

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.

werner
  • 13,518
  • 6
  • 30
  • 45
  • This looks correct, but could you elaborate more on the top equation? Why does removing parentheses change the equation like this? – Steven Jun 25 '18 at 20:20
  • @soulzek the reason for the difference is the minus sign before the parentheses. Please check the links in my answer – werner Jun 25 '18 at 20:35
  • 1
    @Steven Nevermind, LUA is resolving it left-to-right without parentheses. Subtract is a noncommutative mathematical operation where as + is, hence the confusion in my brain. This is what the code turns into: first line: 5-(3-1) = 2 second line: (5-3)-1 = 1 – soulzek Jun 25 '18 at 20:35