Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the error message of a lua function called with lua_pcall geting lost

Tags:

c++

lua

I'm using lua 5.1 and I'm using lua to load functions that can then be called from C++.

int Error = luaL_loadfile(LuaState, "Test.lua");
if(!Error)
{
    Error = lua_pcall(LuaState, 0, LUA_MULTRET, 0);
}
if(Error)
{
    std::cerr << "-- " << lua_tostring(LuaState, -1) << std::endl;
    lua_pop(LuaState, 1);
}
else
{
    LuaStackBalancer LSB(LuaState); //Puts the Lua Stack back to the way it was found
    lua_pushstring(LuaState, "Run");
    lua_gettable(LuaState, LUA_GLOBALSINDEX);
    if(lua_isfunction(LuaState, -1))
    {
        if(lua_pcall(LuaState, 0, 0, 0))
        {
            std::cerr << "-- " << lua_tostring(LuaState, -1) << std::endl;
        }
    }
}

The problem is that if the lua function that I call from C++ calls another function that errors out then the return is the first argument of that function instead of the error message.

AlwaysErrorsOut defined as:

int AlwaysErrorsOut(lua_State *LuaState) 
{ 
    return luaL_error(LuaState, "Error Test Successful"); 
}

Lua Test 1:

--Test.lua
AlwaysErrorsOut("Weirdness is happening")

Out:

-- Test.lua:1: Error Test Successful

Lua Test 2:

--Test.lua
function Run()
    AlwaysErrorsOut("Weirdness is happening")
end

Out:

-- Weirdness is happening

My current theory is that after the error happens the error message is placed on top of the stack and the stack is then reduced to 1.

Anyone know how to prevent the loss of the error message?

like image 349
khm Avatar asked Nov 14 '22 21:11

khm


1 Answers

The problem was with some bit of my code i had completely overlooked, in it i had another LuaStackBalancer object that was created and its destructor was called when the error was thrown resulting in the loss of the error message. ^^u

Thank you all for your help and please forgive my stupidity

like image 115
khm Avatar answered May 13 '23 04:05

khm