title: Lua: Code optimization vector length calculation
body: <p>I have a script in a game with a function that gets called every second. Distances between player objects and other game objects are calculated every second there. The problem is that there can be thoretically 800 function calls in 1 second(max 40 players * 2 main objects(1 up to 10 sub-objects)). I have to optimize this function for less processing. this is my current function:</p>
  
  <pre><code>local square = math.sqrt;
  
  local getDistance = function(a, b)
      local x, y, z = a.x-b.x, a.y-b.y, a.z-b.z;
      return square(x*x+y*y+z*z);
  end;
  
  -- for example followed by: for i = 800, 1 do getDistance(posA, posB); end
  </code></pre>
  
  <p>I found out, that the localization of the math.sqrt function through</p>
  
  <pre><code>local square = math.sqrt;
  </code></pre>
  
  <p>is a big optimization regarding to the speed, and the code</p>
  
  <pre><code>x*x+y*y+z*z
  </code></pre>
  
  <p>is faster than this code:</p>
  
  <pre><code>x^2+y^2+z^2
  </code></pre>
  
  <p>I don't know if the localization of x, y and z is better than using the class method "." twice, so maybe <code>square(a.x*b.x+a.y*b.y+a.z*b.z)</code> is better than the code <code>local x, y, z = a.x-b.x, a.y-b.y, a.z-b.z;
              square(x*x+y*y+z*z);</code></p>
  
  <p>Is there a better way in maths to calculate the vector length or are there more performance tips in Lua?</p>