lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

> On 13 Mar 2015, at 13:58, Eric Wing <> wrote:
> On 3/13/15, Colin <> wrote:
>> Hi,
>> following the announcement of Lua 5.3 with the greatly appreciated addition
>> of native integer support we are planning to update a bunch of C++ projects
>> from Lua 5.1 and were wondering how the compatibility with C++ exceptions
>> has progressed.
>> The scenario that we are looking at is
>> C++ application
>> calls
>> Lua function
>> calls
>> C++ function
>> when the inner C++ function throws an exception.
>> Currently we handle this situation at the Lua-to-C++ call point by wrapping
>> the C++ function in a try-catch block that logs an exception and calls the
>> Lua error function; at the C++-to-Lua transition we detect the Lua error and
>> then throw a C++ exception.
>> (With C++11 we could improve this approach by extending the Lua state by a
>> std::exception_ptr, storing the exception caught at the Lua-to-C++
>> transition there, and re-throwing it at the C++-to-Lua point.)
>> The question is, can this be simplified?
>> Ideally the C++ exception would simply "fly through" the Lua interpreter
>> from the inner C++ function to the outside C++ application, but as far as I
>> understand, that is not, or at least: was not possible because Lua obviously
>> can't use RAII and requires an explicit call to its error handling
>> facilities to keep everything consistent.
>> If this "flying through" does not work unmodified, is it possible to somehow
>> "patch up" things, i.e. let the exception fly through and then afterwards,
>> in a try-catch at the C++-to-Lua point, call some Lua function to put things
>> back into a consistent state? (This would allow leaving out the try-catch
>> around the inner C++ function and not require adding the exception_ptr to
>> the Lua state to recover the original exception.)
>> Or what else is the recommended way of handling this interoperability
>> question, what is the current "best practice"?
>> Thanks, Colin
> So I think the expected practice is to compile Lua's ldo.c as C++. It
> will define Lua's internal mechanism for pcall to use try/catch
> instead of setjmp/longjmp. Then if a C++ exception does occur, pcall
> will be aware of it and catch it and then you just do the normal error
> handling thing. No need to do anything elaborate.

That makes sure that Lua doesn’t end up in an inconsistent state, but it doesn’t solve the bigger issue:

With a "outer C++ calls Lua calls inner C++" call-chain you really want the outer C++ to be able to catch the exception thrown by the inner C++ function.

Regards, Colin