Question

When lua code causes an exception, luabind will leave an error message on the stack for me to collect. I am wondering how to guarantee that the lua stack will be in a sensible state after I have handled the exception:

  1. The examples I've found tells me to use luabind::from_stack(e.state(), -1). Won't this leave the error message still on the stack? Shouldn't I pop it?

  2. Is it sufficient to pop the error message from the stack? Does the error cause other garbage to be left on the stack?

How do I make sure that the lua state is good after an error has occurred?

This is what I've got:

try  {
    // Do lua-stuff here that causes an exception from lua
}
catch (const luabind::error& e) {
    luabind::object error_msg(luabind::from_stack(e.state(), -1));

    std::stringstream ss;
    ss << error_msg;

    throw my_own_exception_class(ss.str());
}
Was it helpful?

Solution

  1. It will leave the error message on the stack. Whether you should pop it depends entirely on what you are doing with the stack next. If you don't need the message anymore (since you saved it somewhere else) then pop it. If you are going to use it further down the catch chain, then leave it. The point is, you use the Lua stack to communicate with the Lua API, what you have on it depends entirely on what you want to tell the API.

  2. There are two ways to interpret "garbage" here:

    • As in "the Lua stack has compromised internal structure and any call to lua_XXX functions will SEGFAULT/crash/etc". This should never happen no matter what C++ exceptions you throw around, it's Luabind responsibility to guard against that. Any C++ exceptions are thrown and handled by Luabind as Lua itself is written in C and in its world there are no such things as exceptions.

    • As in "there are some values on the stack I no longer need". There shouldn't be garbage left on the stack. If you feel paranoid, feel free to clear the stack with lua_settop(0) before any chain of Lua API calls

OTHER TIPS

Simplest way is probably this

 int luaErr = luaL_dofile(luaState, "main.lua"); // or other lua stuff
 if (luaErr != 0)
      std::cout << "Lua error: " << lua_tostring(luaState, -1) << std::end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top