سؤال

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.

هل كانت مفيدة؟

المحلول 2

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.

نصائح أخرى

The function luaL_error() will call exit() which cancels the whole execution of your program! The desctructor is not called then because the scope where Test t is in does not end. You should use a different functionality to be able to recover from an error.

How do you call the error from lua? I think you need to do a protected call using lua_cpcall to go arround this exit on error feature!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top