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?
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:
Build:
Check:
Test:
Obtain test program here (C/C++ mixed, sorry). Build it via:
Output: