I want to run a python script from my lua file. How can I achieve this?
Example:
Python code
#sum.py file
def sum_from_python(a,b)
return a+b
Lua code
--main.lua file
print(sum_from_python(2,3))
Sounds like Lunatic-Python does exactly what you're looking for. There's a fork of lunatic-python that's better maintained than the original. I've contributed several bug fixes to it myself awhile back.
So reusing your example,
# sum.py
def sum_from_python(a, b):
return a + b
-- main.lua
py = require 'python'
sum_from_python = py.import "sum".sum_from_python
print( sum_from_python(2,3) )
lua main.lua
5
Most of the stuff works as you would expect but there are a few limitations to lunatic-python.
As for lupa, note that it is a python module only, which means you must use python as the host language -- it does not support the use-case where lua is the "driving" language. For example, you won't be able to use lupa from a lua interpreter or from a C/C++ application that embeds lua. OTOH, Lunatic-Python can be driven from either side of the bridge.
I see these as your options:
Don't do it: I agree with others' suggestions that you should find a way to do it in pure Lua, but perhaps you have a real requirement to integrate the two.
You could use SWIG (www.swig.org) to export the Lua C API to Python. You might save yourself some time by using a C++ binding (like lua-icxx.sf.net) but that really depends on your requirements.
You could use an existing library; lunatic python is dead AFAIK, but LUPA seems in good health (https://pypi.python.org/pypi/lupa).
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