C++ – Redirecting/redefining print() for embedded Lua

clua

I have embedded Lua in my C++ application. I want to redirect print statements (or maybe simply redefine the print function?), so that I can display the evaluated expression somewhere else.

What is the best way to do this: redirect or redefining the print() function?

Any snippets/pointers to snippets that show how to do this would be much appreciated.

Best Answer

You can redefine the print statement in C:

static int l_my_print(lua_State* L) {
    int nargs = lua_gettop(L);

    for (int i=1; i <= nargs; i++) {
        if (lua_isstring(L, i)) {
            /* Pop the next arg using lua_tostring(L, i) and do your print */
        }
        else {
        /* Do something with non-strings if you like */
        }
    }

    return 0;
}

Then register it in the global table:

static const struct luaL_Reg printlib [] = {
  {"print", l_my_print},
  {NULL, NULL} /* end of array */
};

extern int luaopen_luamylib(lua_State *L)
{
  lua_getglobal(L, "_G");
  // luaL_register(L, NULL, printlib); // for Lua versions < 5.2
  luaL_setfuncs(L, printlib, 0);  // for Lua versions 5.2 or greater
  lua_pop(L, 1);
}

Since you are using C++ you'll need to include your file using 'extern "C"'

Related Topic