title: Lua set default error handler
body: <p>The default <code>lua_pcall</code> error handler (as of Lua 5.3) does nothing, letting the exception message remain on top of the stack. We would like to change this so we get a <code>luaL_traceback</code> traceback in addition to the exception message on top of the stack on <code>lua_pcall</code> failure.</p>
  
  <p>Unfortunately I think that means we need to insert the error handler just below all of our pcalls. The most robust way of doing this seems to be like this:</p>
  
  <pre><code>/* push function and arguments */
  lua_pushstuff...
  
  /* push error handler */
  lua_pushcfunction(L, my_error_handler);
  
  /* move the error handler just below the function and arguments */
  lua_insert(L, -(number of args + 1));
  
  if (lua_pcall(L, nargs, nresults, -(number of args + 1))) {
      /* error here (my_error_handler was invoked) */
      /* do something with lua_tostring(L, -1) */
  }
  
  /* afterwards, pop the error handler (it may be below return values) */
  lua_pop(L, 1);
  </code></pre>
  
  <p>But this introduces noise at each pcall (we have quite a few, since we have some Lua callbacks called asynchronously from C) and feels kind of repetitive. I thought this could be wrapped inside some <code>lua_mypcall</code> function that does this setup work automatically, but I have two questions:</p>
  
  <ol>
  <li><p>is this approach liable to break with more complex stack manipulation before (or inside) the pcall? (I'm not super well versed in the Lua stack yet)</p></li>
  <li><p>since we'd like the traceback on the majority of pcalls, it makes sense to make this error handler the default, and having the previous error handler (that does nothing) be specified manually, so is there a way to globally change the default error handler for the Lua state?</p></li>
  </ol>
  
  <p>I saw that <code>lua_pcallk</code> has some code for <code>errfunc == 0</code>, but it doesn't seem configurable. We could hack the Lua implementation to change the default manually, but would like to avoid that.</p>
  
  <p>We are using Lua 5.3. Thanks.</p>