Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to handle C++ exceptions when calling functions from Lua?
    text
    copied!<p>I have a working C++ function that I am able to call from Lua. To demonstrate my problem here is an example:</p> <pre><code>int PushHello(lua_State *L){ string str("Hello"); lua_pushlstring(L, str.data(), str.length()); return 1; } </code></pre> <p>Note: I know I don't have to use string variable there, but it is there to demonstrate the problem.</p> <p>Here are my two problems:</p> <ol> <li><p>When I call this function from Lua string constructor may throw an exception. Is that a problem? Will Lua handle it and unwind the Lua stack properly? I don't think so. How can I solve that? Do I need to add <code>try/catch</code> around all such code and convert the exception to lua_error? Is not there a better solution?</p></li> <li><p>Another problem that I have probably solved by compiling Lua as C++ is when <code>lua_pushlstring()</code> calls <code>lua_error()</code> string destructor would not be called if longjmp was used. Is the problem solved by compiling as C++ and throwing exceptions instead of using longjmp?</p></li> </ol> <p>To clarify, possible solution I can see to problem 1 would be this:</p> <pre><code>int PushHello(lua_State *L){ string str; try{ str.assign("Hello"); catch(exception &amp;e){ luaL_error(L, e.what()); } lua_pushlstring(L, str.data(), str.length()); return 1; } </code></pre> <p>But that is very ugly and error prone as <code>try/catch</code> would need to be added to many places. It could be done as a macro and put around every command that can throw, but that would not be much nicer.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload