Sam H
Sam H

Reputation: 976

Lua Interpreter Question

How do I get the output from the following:

lua_pushstring(L,"print(i)");
lua_call(L,0,0);

Upvotes: 2

Views: 572

Answers (3)

Zecc
Zecc

Reputation: 4340

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.

Upvotes: 3

Mud
Mud

Reputation: 28991

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

Upvotes: 2

Mike Caron
Mike Caron

Reputation: 14561

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...

Upvotes: 0

Related Questions