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?
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
This answer can get critics from some readers, but first please have a look at my blog post which I've prepared specially for this answer, and read the foreword why I choose this solution.
As promised, I've upstreamed 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.x.y-redirect.a | grep printf
nm liblua-5.x.y-redirect.a | grep fputs
nm liblua-5.x.y-redirect.a | grep fwrite
Test:
Obtain test program here (C/C++ mixed, sorry). Build it via:
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)
---
Lua's I/O library probably covers what you're looking for. The io.output
function lets you set the default output file. Check out the I/O library section in the 5.2 manual to see what else is there.
Why do you want to reroute the output? You say you want to manipulate it in some way, but what do you mean by that?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With