title: Can I inject a function into a Lua function?
body: <p>So if I have this lua function</p>
  
  <pre><code>function dostuff(x) 
     function foo () x=x+1; end
     foo(); 
     return x; 
  end
  </code></pre>
  
  <p>And it turns out i need foo many times. But it is mainly useful because it has access to the x upvalue. Is there a way to pull foo out of dostuff, but still have it access to x? </p>
  
  <p>I tried to put foo() global and adding it to dostuff, like this:</p>
  
  <pre><code>function foo () x=x+1; end
  function dostuff(x) 
     foo(); 
     return x; 
  end
  dostuff.foo = foo
  </code></pre>
  
  <p>Which does not work as in lua functions are distinct from tables (unlike js). 
  I still have a feeling that this does work in lua, probably using metatables. But I just not know enough about it yet. I know a lot of ways to avoid this and work around it. I am just curious if there is a way to do it. </p>
  
  <p>Maybe another way to look at is, can you call a global function with a choice of closure? </p>