2

How do I get the output from the following:

lua_pushstring(L,"print(i)");
lua_call(L,0,0);
user229044
  • 232,980
  • 40
  • 330
  • 338
Sam H
  • 956
  • 4
  • 16
  • 24

3 Answers3

3

If you want to run arbitrary Lua code from C, what you need to use is luaL_dostring, as in this question: C & Lua: luaL_dostring return value

Edit: please note that Lua's default print function will still print its output straight to the console. You will need to redirect stdout in some way (probably to a pipe) if you want to capture its output.

Community
  • 1
  • 1
Zecc
  • 4,220
  • 19
  • 17
2

That code shouldn't work at all. You're attempting to call a string. You need to push a function value onto the stack, then call lua_call.

lua_getglobal(L, "print");          // push print function onto the stack
lua_pushstring(L, "Hello, World!"); // push an argument onto the stack
lua_call(L,1,0);                    // invoke 'print' with 1 argument
Mud
  • 28,277
  • 11
  • 59
  • 92
0

If you mean the return value, it will be on the top of the stack.

If you meant the output from the print statement... that's a bit more difficult. The suggestion I read here is to replace print with a custom function that does what you need.

Of course, this is a bit complex, and I haven't touched lua in a while...

Mike Caron
  • 14,351
  • 4
  • 49
  • 77