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,
Python code:
# sum.py
def sum_from_python(a, b):
return a + b
Lua code:
-- main.lua
py = require 'python'
sum_from_python = py.import "sum".sum_from_python
print( sum_from_python(2,3) )
Outputs:
lua main.lua
5
Most of the stuff works as you would expect but there are a few limitations to lunatic-python.
It's not really thread-safe. Using the python threading library inside lua will have unexpected behavior.
No way to call python functions with keyword arguments from lua. One idea is to emulate this in lua by passing a table but I never got around to implementing that.
Unlike lupa, lunatic-python only has one global lua state and one python VM context. So you can't create multiple VM runtimes using 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.