Freakyy
Freakyy

Reputation: 365

Lua Catching Exceptions

I am coding in Lua (and C++). I want to catch exceptions and printing them into console. After lua_atpanic did not work correctly (program exited anyway). I thought to use exceptions.

Here is the edited part of my luaconf.h:

/* C++ exceptions */
#define LUAI_THROW(L,c) throw(c)
#define LUAI_TRY(L,c,a) try { a } catch(...) \
{ if ((c)->status == 0) (c)->status = -1; }
#define luai_jmpbuf int  /* dummy variable */

Here is the init.lua loaded:

int init = luaL_loadfile(L, "lua/init.lua");
if(init == 0)
{
    printf("[LUA] Included lua/init.lua\n");
    init = lua_pcall(L, 0, LUA_MULTRET, 0);
}

So now I thought, when using C++ exceptions I would edit that code to the following:

try {
    int init = luaL_loadfile(L, "lua/init.lua");

    if(init == 0)
    {
        printf("[LUA] Included lua/init.lua\n");
        init = lua_pcall(L, 0, LUA_MULTRET, 0);
    }

    // Error Reporting
    if(init != 0) {
        printf("[LUA] Exception:\n");
        printf(lua_tostring(L, -1));
        printf("\n\n");
        lua_pop(L, 1);
    } else {
        lua_getglobal(L, "Init");
        lua_call(L, 0, 0);
    }
} catch(...)
{
    MessageBox(NULL, "Hi", "Hio", NULL);
}

Just to see if anything happens. But nothing happens. (The Lua error is calling a nil value)

Any ideas?

Upvotes: 0

Views: 6799

Answers (1)

mtsvetkov
mtsvetkov

Reputation: 842

From this you can see that lua_atpanic will always quit the application unless you do a long jump from within the panic function.

And from this you can see that calling lua_pcall(L, 0, LUA_MULTRET, 0) will push an error message to the stack when you don't give it a stack location (errfunc is 0).

Since Lua is a C library, it does not use exceptions (C++ exceptions that is), so you will never catch such a beast from Lua code. Your code however can throw exceptions. To do this you'll have to compile the Lua library as C++.

Further reading:

How to handle C++ exceptions when calling functions from Lua? and

What is the benefit to compile Lua as C++ other than avoid 'extern C' and get 'C++ exception'?

Upvotes: 4

Related Questions