title: Is Lua embedded in C++ capable of having persistent local variables? If not, is there a scripting language that does?
body: <p>I have embedded Lua in my C++ application using LuaBind. I need to have variables that persist across multiple runs, that can't be accessed by other objects that run the same file name. </p>
  
  <p>For example: let's say I have a class called <code>NPC</code>. An <code>NPC</code> holds a string, that is the name of the script they run. When an <code>NPC</code> is created, a variable is created called <code>Health</code>. When an <code>NPC</code> is hit, they lose 5 health. The scripts would be something like this in Lua:</p>
  
  <pre><code>local health = 10
  
  function onHit()
      health = health - 5
  end
  </code></pre>
  
  <p>The issue I have with this is that every <code>NPC</code> that runs this script, doesn't have their own instance of health. For example, let's say I create <code>NPC A</code>, and subtract 5 from its health. Then, I create <code>NPC B</code>. Because it resets health back to 10, if I tell <code>NPC A</code> to print health, it gives me back 10, even though it should be 5.</p>
  
  <p>If I were to have a different Lua instance for every object, then it would work that way, but I would end up with hundreds of instances at a time in that case, which I understand is not a good thing.</p>
  
  <p>Is there a way to have variables work like this in Lua? If not, is there a scripting language that will work like this in an efficient manner?</p>
  
  <p>For reference, here is the code I am testing:</p>
  
  <p>Lua:</p>
  
  <pre><code>local health = 10;
  
  function onHit()
      health = health - 5
      print_out(health)
  end
  </code></pre>
  
  <p>C++:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>class NPC
  {
  public:
     NPC(lua_State* inState);
     void onHit();
  
     const char* behavior;
     lua_State* luaState;  
  };
  
  NPC::NPC(lua_State* inState)
  {
     luaState = inState;
     behavior = "testBehavior.lua";
     luaL_dofile(luaState, behavior);
  }
  
  void NPC::onHit()
  {    
     luaL_loadfile(luaState, behavior); 
     luabind::call_function&lt;int&gt;(luaState, "onHit");
  }
  
  void print_out(int number) {
     cout &lt;&lt; "Health : " &lt;&lt; number &lt;&lt; endl;
  }
  
  int main() 
  {
     lua_State *myLuaState = luaL_newstate();
     luabind::open(myLuaState);
  
     luabind::module(myLuaState) [
        luabind::def("print_out", print_out)
     ];
  
     NPC test(myLuaState);
     NPC test2(myLuaState);
     test.onHit();
     test2.onHit();
     test.onHit();
  
     lua_close(myLuaState);
  }
  </code></pre>