title: How to identify uninitialized variables in a Lua script, without running it
body: <p>I'd like to be able to write some Lua code like this:</p>
  
  <pre><code>y=x+1
  </code></pre>
  
  <p>and be able to get the names of all variables (<code>x</code> and <code>y</code> in this case) so that I can read from/write to them in the calling C++ program. The problem is that <code>x</code> is uninitialized, so this chunk will not execute and therefore neither variable will appear in the globals table. My current work-around is to have the user explicitly declare that they want to initialize <code>x</code> externally (as well as <em>how</em> to initialize it), then I pre-pend the Lua script with an appropriate declaration for <code>x</code>, so that the final script looks like this:</p>
  
  <pre><code>x= /*some value calculated outside of the Lua script*/
  y=x+1
  </code></pre>
  
  <p>Although this works, I'd really like to have a way to automatically list all uninitialized variables in the Lua code and present them to the user, instead of the user having to remember to explicitly declare them. A function that parses the Lua code without executing it would probably be what I want. I've tried the function <code>luaL_loadstring</code>, but <code>x</code> and <code>y</code> don't show up in the globals table.</p>
  
  <p>Since this is a bit vague, I'll give an actual use case. My C++ code basically performs optimizations on functions, such as finding a root or a maximum. I want the user to be able to define custom functions (in the form of Lua scripts), which in general will have one or more inputs and one or more outputs. The user will define which parameters the optimizer should operate on. For example, the user may want to find the minimum of <code>y=x^2</code>. The way I'd like it to work is that the user writes a Lua script consisting of nothing more than <code>y=x^2</code>, and then tells the optimizer to vary <code>x</code> in order to minimize <code>y</code>. On each iteration of the optimizer, the current guess for <code>x</code> would be automatically pasted into the user script, which is then executed, and then the value of <code>y</code> is pulled from the Lua state to be fed back to the optimizer. This is how I have it working now, however it's a bit clumsy from a UX perspective because the user has to manually declare that <code>x</code> is a Lua variable. This gets tedious when there are many variables that require manual declaration. It would be much better if I could automatically scan the script and show the user a list of their undeclared variables so they could then use drag-and-drop and other GUI sugar to do the manual declaration.</p>