2

I have a Lua expression, which can print some string. For example: print(1+2). Then, I call this expression in Python 3 using Lupa library:

import lupa

lua = lupa.LuaRuntime(unpack_returned_tuples=True)
res = lua.eval('print(1+2)')

Of course, res is None because this expression returns nothing. But I need to catch the output and save in the variable.

Is this possible? How can I do this?

VeLKerr
  • 2,995
  • 3
  • 24
  • 47
  • Have you tried [this](http://stackoverflow.com/a/16571630/3005167)? I do not know if `lupa` cares about `sys.stdout`, but it's worth a try. – MB-F Feb 19 '16 at 12:35
  • @kazemakase, I have just tried it but it doesn't work for me. Firstly, I replaced `cStringIO` to `io` because I've working on Python 3. So, when I ran following code: `with Capturing() as output: lua.eval('print(1+2)') print(output)`, **I've got an empty list output**. – VeLKerr Feb 19 '16 at 13:18

1 Answers1

2

I've never used Python, but I think you need to do this:

import lupa

lua = lupa.LuaRuntime(unpack_returned_tuples=True)
res = lua.eval('1+2')

res should now be 3, which you can print from Python. If you want Lua to print it instead, you'll have to use execute:

res = lua.execute('local v = 1+2 print(v) return v')

(Based on similar questions that had those code examples)

EinsteinK
  • 745
  • 3
  • 8