title: Lua: How to properly clean up errors returned by lua_pcall
body: <p>I've been having a crash problem with Lua for a little while now, and I finally discovered what I believe to be the problem. I'm allowing the script to omit functions that are attempted to be called for convenience. I want my application to attempt to invoke TestFun (as an example), and if it exists then execute it, otherwise gracefully and silently fail.</p>
  
  <p>The problem I was having was that I simply invoked lua_pcall(L, 0, 0, 0) and ignored the return value because it didn't matter to me. What I discovered was that when Lua generates the error "attempt to call nil" it places this on its stack and I was not popping this off. The code below exhibits a crash shortly after being run due to the stacksize growing too large:</p>
  
  <pre><code>int _tmain(int argc, _TCHAR* argv[])
  {
      std::string script = "";
      lua_State* L = luaL_newstate();
      luaL_openlibs(L);
      luaL_loadstring(L, script.c_str());
      lua_pcall(L, 0, LUA_MULTRET, 0);
  
      while (true)
      {
          lua_getglobal(L, "TestFunc");
          lua_pcall(L, 0, 0, 0);
      }
  
      return 0;
  }
  </code></pre>
  
  <p>I simply modified my code inside the while loop to be:</p>
  
  <pre><code>while (true)
  {
      lua_getglobal(L, "TestFunc");
      if (lua_pcall(L, 0, 0, 0))
          lua_pop(L, -1);
  }
  </code></pre>
  
  <p>And this solved my crash. My question is whether or not this is valid in all cases of lua_pcall() error results, or if I'm setting myself up for another bug/crash by not specifically checking if I should pop -1 (or possibly others?). Perhaps I should only pop if -1 is a string, or perhaps there's a standard 'cleanup the stack' function I could call?</p>
  
  <p>Thanks</p>