lua-users home
lua-l archive

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


On Fri, 12 Mar 2010, Gaspard Bucher wrote:

> Anyway, my current bindings for OpenCV are working except for C++
> exception handling. I have two options here:
> 
> A. adapt "Dub" to wrap all calls in a try .. catch block and use
> lua_error to push "what()" on the stack

This is what you need to do.  You also may need to protect calls to 
the Lua API with lua_pcall / lua_cpcall if you're relying on RAII or 
other non-POD objects on the stack, since otherwise Lua's longjmp will 
just whizz past your stack frames and not unwind correctly.  The 
safest approach is one where you keep a strict separation between 
contexts where Lua may raise an error and ones where C++ code may 
throw an exception, and never let the two overlap.

Indeed, the one time when I've had to integrate C++ code with Lua I 
ended up writing a pure C interface to the C++ code first and 
converted all C++ exceptions using try/catch/what() at the C <-> C++ 
boundary.  After that it was smooth sailing to bind the Lua code to 
the C API.

You may opt to target Lua VMs which are compiled to use your 

compiler's C++ exceptions instead of setjmp/longjmp error handling, 
but I don't know very much about this so hopefully others can chime in 
on how to make this option work best.  Looking at the code in 
luaconf.h, it looks like Lua does not extract any sensible error 
object from exceptions which it didn't raise itself.  Based on a quick 
test it looks like if Lua pcalls a lua_CFunction which throws a C++ 
exception then the error object is then the lua_CFunction itself, 
regardless of what the exception is.

Cheers,

Joonas