Send lua output to non stdout

I have a c program with built-in Lua. at the moment it's just a hello world. however, before moving on, I would like to get lua output to send somewhere other than stdout so that I can somehow manipulate it. Here is 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 would like to use the result seen in the comments to print the result of the lua code twice. It can be done?

+4
source share
3 answers

This answer may receive criticism from some readers, but first, please look at my blog post , which I prepared specifically for this answer, and read the introduction, why I choose this solution.

As promised, I updated my old Lua 5.1 output redirection patch to the latest version.
Patches are available here: 5.1.5 and 5.2.1 .

Patch

 patch -p1 < ~/download/lua-5.2.1-output-redirect.patch 

Build

 cd src make a LUA_A="liblua-5.2.1-redirect.a" SYSCFLAGS="-DLUA_USE_LINUX -DLUA_REDIRECT" SYSLIBS="-Wl,-E -ldl -lreadline -lncurses" 

Check

 nm liblua-5.xy-redirect.a | grep printf nm liblua-5.xy-redirect.a | grep fputs nm liblua-5.xy-redirect.a | grep fwrite 

Test

Get the test program here (C / C ++ mixed, sorry). Build it through:

 g++ -DLUA_REDIRECT -I/path/to/lua-5.2.1/src/ -L. lua-redirect-test.cpp -llua-5.2.1-redirect -ldl -o lua-redirect-test 

Output:

 ===== Test 1 output ===== Lua stdout buffer: --- hello world! --- Lua stderr buffer: --- --- Lua error message: --- (null) --- ===== Test 2 output ===== Lua stdout buffer: --- --- Lua stderr buffer: --- --- Lua error message: --- [string "bad_function()"]:1: attempt to call global 'bad_function' (a nil value) --- 
+4
source

If your Lua code will use print to output data, then I think the easiest way is to override print from Lua itself. Something like that:

 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 
+5
source

The Lua I / O library probably covers what you are looking for. The io.output function allows io.output to set the default output file. Check out the I / O library section in the 5.2 manual to find out what else is there.

Why do you want to redirect the output? You say you want to manipulate it somehow, but what do you mean by that?

+1
source

All Articles