the error message of a lua function called with lua_pcall geting lost
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?
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
Seems to work fine when completely converted to Lua (see below.) Perhaps the problem is that the lua_pcall
is set for no return values. Try using LUA_MULTRET
instead of 0
on the call to 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
精彩评论