Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting/redefining print() for embedded Lua

Tags:

c++

c

lua

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.

like image 512
skyeagle Avatar asked Dec 22 '10 10:12

skyeagle


2 Answers

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"'

like image 78
Mike M. Avatar answered Sep 22 '22 20:09

Mike M.


You can simply redefine print from a Lua script.

local oldprint = print
print = function(...)
    oldprint("In ur print!");
    oldprint(...);
end
like image 37
Puppy Avatar answered Sep 22 '22 20:09

Puppy