So this is just a real quick post. I wanted to wrap all Lua output to my console so I did. Its pretty simple, although if your still using Lua 5.0 getting errors is different(and I’m guessing obsolete) and I’m going to show you anyways.
Firstly Lua’s 5.0 method. See in 5.0 when an error happens a function called _ALERT is called so you wrap it, well override it.
int LuaError( lua_State *L )
const char* str = lua_tostring( L, -1 );
//send string wherever in my case the console
//now register it to a state
lua_register( L_, "_ALERT", LuaError );
Now when I show you the 5.1 way of doing it, you’ll see just how different it is. In Lua 5.1 they scrapped _ALERT at least it looks that way. Instead if execution doesn’t return 0 you’ve got an error then you just pop it off the stack.
//same for lua_resume, luaL_dofile, etc
int ret = luaL_dostring(state, input_str);
if(ret != 0)
const char *out = lua_tostring(state, -1);
Thats it no need to bind a function. Personally I like the 5.1 method. I do see the advantages of having Lua call the function itself, but I prefer Lua’s 5.1 method.
Wrapping the print() function
This one will require you to override the built in print function. Ours will behave the same since I ripped it straight from lbaselib.c 🙂
Its really the only way to change the output. See the built in one use fputs to print to stdout. We don’t want that. So the only thing we’ll be changing is how its managed and where its sent.
int LuaPrint(lua_State *L)
int nArgs = lua_gettop(L);
std::string ret;//this is where we will dump the output
//make sure you start at 1 *NOT* 0
for(i = 1; i <= nArgs; i++)
const char *s;
lua_call(L, 1, 1);
s = lua_tostring(L, -1);
if(s == NULL)
return luaL_error(L, LUA_QL("tostring") " must return a string to ", LUA_QL("print"));
if(i > 1) ret.append("\t");
//Send it wherever
//same as before register it with the state
lua_register(MainState, "print", LuaPrint );
Now lets test it out 🙂
Yes I know its that same pong test again
So yeah it works. And if your getting tired of seeing that pong test and are wondering when I’ll show something new, I’m working it. I’m currently getting md5mesh/md5anim files loading and rendering correctly, thats why. Right now they look off(well totally fucked up).