lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]




> Is there some sample source code showing how to use lua_pcall with
> err_func != 0?  Basically when I'm calling into Lua and an error
> occurs I'd like to see the debug traceback, but I'm not quite sure how
> to do that based on the docs.

Debug traceback has to be called before you return from a pcall because
the stack is unwound afterwards.

Untested, from memory:

static int err_func_l (lua_State *L)
{
	printf("Error report: %s\n", lua_tostring(L, -1)); // err
message

	lua_pushliteral(L, "debug");
	lua_gettable(L, LUA_GLOBALSINDEX);
	lua_pushliteral(L, "traceback");  // correct fn name?
	lua_gettable(L, -2);
	lua_pcall(L, -1); // call "debug.traceback()"
}

void init(lua_State *L)
{
	lua_register(L, "err_func", err_func_l);
	lua_register(L, "foo", foo_l);
}

void call_my_func(lua_State *L)
{
	lua_pushliteral(L, "err_func");

	// call Lua fn foo with "C prototype" number foo(number)

	lua_pushliteral(L, "foo");
	lua_gettable(L, LUA_GLOBALSINDEX);

	lua_pushnumber(L, <arg1>);

	int ret = lua_pcall(L, 1, 1, -3);

	if (ret != 0)
	{
		// error -- deal with it...
		return;
	}

	lua_Number retValue = lua_tonumber(L, -1);

	lua_pop(L, 1+1); // pop err func and return value
}