Print stacktrace from C code with embedded lua

后端 未结 4 1976
温柔的废话
温柔的废话 2020-12-31 01:54

If I understand this correctly, Lua by default will call the debug library \"debug.traceback\" when an error occurs.

However, when embedding Lua into C code like don

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 02:52

    Working off Nicol’s answer above here is a working example:

    static int traceback(lua_State *L) {
        lua_getfield(L, LUA_GLOBALSINDEX, "debug");
        lua_getfield(L, -1, "traceback");
        lua_pushvalue(L, 1);
        lua_pushinteger(L, 2);
        lua_call(L, 2, 1);
        fprintf(stderr, "%s\n", lua_tostring(L, -1));
        return 1;
    }
    
    int main(int argc, char **argv) {
        lua_State *L = lua_open();
        luaL_openlibs(L);    
        lua_pushcfunction(L, traceback);
        int rv = luaL_loadfile(L, "src/main.lua");
        if (rv) {
            fprintf(stderr, "%s\n", lua_tostring(L, -1));
            return rv;
        } else {
            return lua_pcall(L, 0, 0, lua_gettop(L) - 1);
        }
    }
    

提交回复
热议问题