Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

need traceback info where a calling lua code error occurs. #280

Open
tungfaifong opened this issue Jan 23, 2022 · 1 comment
Open

need traceback info where a calling lua code error occurs. #280

tungfaifong opened this issue Jan 23, 2022 · 1 comment
Labels
feature New LuaBridge feature

Comments

@tungfaifong
Copy link
Contributor

when I call lua code, an error occurs, but there is only error message, sometimes need some calling stack info.
it will be better where an lua error occurs, append a traceback to error message.

@dmitry-t dmitry-t added the feature New LuaBridge feature label Apr 14, 2022
@kunitoki
Copy link

Can't you use lua_pcall and pass a error handler which does lookup the lua debug.traceback and prints it ?

inline int traceback(lua_State* L)
{
    // look up Lua's 'debug.traceback' function
    lua_getglobal(L, "debug");
    if (!lua_istable(L, -1))
    {
        lua_pop(L, 1);
        return 1;
    }

    lua_getfield(L, -1, "traceback");
    if (!lua_isfunction(L, -1))
    {
        lua_pop(L, 2);
        return 1;
    }

    lua_pushvalue(L, 1);
    lua_pushinteger(L, 2);
    lua_call(L, 2, 1);
    
    lua_getglobal(L, "print");
    if (!lua_isfunction(L, -1))
    {
        lua_pop(L, 1);
        return 1;
    }

    lua_pushvalue(L, 1);
    lua_call(L, 1, 0);
    
    return 1;
}

int main()
{
    lua_pushcfunction(L, &traceback);

    if (luaL_loadstring(L, "<your script here>") != LUABRIDGE_LUA_OK
        || lua_pcall(L, 0, 0, -2) != LUABRIDGE_LUA_OK)
    {
        auto errorString = lua_tostring(L, -1);
        std::cerr << (errorString ? errorString : "Unknown lua error") << "\n";
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New LuaBridge feature
Projects
None yet
Development

No branches or pull requests

3 participants