title: Difference in Closures between Javascript and Lua
body: <p>Why is it that these two seemingly identical pieces of code behave differently in Javascript and Lua?</p>
  
  <p>Lua:</p>
  
  <pre class="lang-lua prettyprint-override"><code>function main()
      local printFunctions={}
      local i,j
      for i=1,10 do
          local printi = function()
              print(i)
          end
          printFunctions[i]=printi
      end
      for j=1,10 do
          printFunctions[j]()
      end
  end
  main()
  </code></pre>
  
  <p>Javascript:</p>
  
  <pre class="lang-js prettyprint-override"><code>function main()
  {
      var printFunctions=[]
      var i,j;
      for(i=0;i&lt;10;i++)
      {
          var printi = function()
          {
              console.log(i);
          }
          printFunctions[i]=printi;
      }
      for(j=0;j&lt;10;j++)
      {
          printFunctions[j]();
      }
  }
  main()
  </code></pre>
  
  <p>The example in Lua prints <code>0 1 2 3 4 5 6 7 8 9</code>, but the example in Javascript prints <code>10 10 10 10 10 10 10 10 10 10</code>. Can anybody explain the difference between closures in Javascript and Lua that causes this to happen? I'm coming from a Javascript background, so please focus on the Lua side.</p>
  
  <p>I attempted to explain this on <a href="http://flightodyssey.blogspot.com/2013/09/closure.html" rel="noreferrer">my blog</a>, but I'm not sure if my explanation is correct, so any clarification would be appreciated.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Thanks everyone, now I understand. This slightly modified version of the Lua code prints 10,10,10,10,10,10,10,10,10,10 as expected</p>
  
  <pre><code>function main()
      local printFunctions={}
      local i,j,k
      for i=1,10 do
          k=i
          local printi = function()
              print(k)
          end
          printFunctions[i]=printi
      end
      for j=1,10 do
          printFunctions[j]()
      end
  end
  
  main()
  </code></pre>