Send lua output to non stdout

cluastdout

I have a c program running embedded Lua. as of right now, it's just a hello world. before moving on, though, I'd like to be able to get the lua output to be sent somewhere other than stdout, so that I can manipulate it in some manner. Here's my code:

#include <stdio.h>

#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

int main() {
    lua_State *luaVM = luaL_newstate();
    //char result[1024];

    if (luaVM == NULL) {
        printf("Error initializing lua!\n");
        return -1;
    }
    luaL_openlibs(luaVM);
    luaL_dostring(luaVM, "print(\"hello world!\")");
    //Somehow put the output into result

    //printf("%s\n%s\n", result, result);

    lua_close(luaVM);
    return 0;
}

For example, I'd like to use result, seen in the comments, to print the result of the lua code twice. Can this be done?

Best Answer

If your Lua code is going to be using print to output stuff, then I guess the simplest way is to redefine print from Lua itself. Something like this:

print_stdout = print -- in case you need the old behavior

print = function(...)
  for arg,_ in ipairs({...}) do
    -- write arg to any file/stream you want here
  end
end