Lua function error message called with lua_pcall losing

I use lua 5.1 and I use 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 throws errors, then returning is the first argument to this function instead of an error message.

AlwaysErrorsOut is defined as:

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

Lua Test 1:

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

Of:

- Test.lua: 1: error test completed successfully

Lua Test 2:

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

Of:

- a strange thing happens

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

Does anyone know how to prevent the loss of an error message?

+5
source share
2 answers

, , LuaStackBalancer, , , , . ^^

.

+1

, Lua (. ). , , lua_pcall . LUA_MULTRET 0 Run.

local x=loadstring[[
function AlwaysErrorsOut(s)
    error("Test Successfull")
end

function Run()
    AlwaysErrorsOut("Weirdness is happening")
end
]]

local a,b = pcall(x)

print(a) --> true
print(b) --> nil

local a,b = pcall(_G["Run"])

print(a) --> false
print(b) --> [string "function AlwaysErrorsOut(s)..."]:2: Test Successfull
0

All Articles