I have a piece of code like this
class Test
{
public:
Test() {printf(">>> Test()\n");}
~Test() {printf(">>> ~Test()\n");}
}
int myFunc(lua_State *L)
{
Test t;
luaL_error(L, "error");
return 0;
}
I know when lua complied by c complier it use longjmp to raise an error. So, I compiled it use c++ compiler so that it use c++ exception to hand the errors and the destructor should be called even if an error is thrown. But my problem is that the object's destructor is not called.
However, the following code is working (the destructor is called)
int myFunc(lua_State *L)
{
Test t;
throw(1) // just for testing
return 0;
}
Why this happend? I'm sure the LUAI_THROW macro is interpreted as throw key word.
The root cause is related to exception handling mode in visual c++ compiler. I use the lua function (such as luaL_error) with extern "C" modifier to prevent compiler from name-mangling. And the default exception handling mode is /EHsc which assume extern "C" function don't throw exception. So, the exception can't be catched. The solution is change /EHsc to /EHs.
For more information please refer to http://msdn.microsoft.com/en-us/library/1deeycx5.aspx.