Freakyy
Freakyy

Reputation: 365

C++ Lua Error Handling

I am working on a program (C++, with D3D9) and Lua. I already implemented the LUA Api and everything is working fine, beside the error handling. I googled alot and I found a solution that handles most of the errors. I write this because of the other errors.

I will show you some relevant code in pictures.

Code Part 1 (LUA)

Code Part 2 (LUA)

Part 3 (Console Output)

Now the most important functions: PerformCall() and LuaErrorReport()

Part 4 (C++) Part 5 (PerformCall)

However, as I said before: Some errors are being handled. But this one is not.

Upvotes: 4

Views: 6339

Answers (1)

greatwolf
greatwolf

Reputation: 20878

Some thoughts on what could be wrong. You're passing L for lua_pcall while LuaErrorReport gets State() instead. They could be working on different lua_State which can happen like in the context of a coroutine. If this is intentional, at the very least indicate somewhere why this is being done.

The lua_pushvalue inside LuaErrorReport also looks suspicious. How do you know the bottom value on the stack holds the message you're reporting? This function gets called from other functions that may have accumulated more values on the stack. I would either change that to

lua_pushvalue(L, -3);

or

lua_pushstring(L, msg);

Lastly, you should also considering passing debug.traceback as the error function to lua_pcall to get a more meaningful stacktrace error message. Something like:

void LUA::PerformCall(int return_amount)
{
  lua_getglobal(L, "debug");
  lua_getfield(L, -1, "traceback");
  lua_remove(L, -2);
  int errindex = -p_iArgCount - 2;
  lua_insert(L, errindex);
  int error = lua_pcall(L, p_iArgCount, return_amount, errindex);
  // ...

And get rid of the debug.trace call in LuaErrorReport.

Upvotes: 3

Related Questions