[英]How to call a Python function from Lua?
I want to run a python script from my lua file. 我想从我的lua文件中运行一个python脚本。 How can I achieve this?
我怎样才能做到这一点?
Example: 例:
Python code Python代码
#sum.py file
def sum_from_python(a,b)
return a+b
Lua code Lua代码
--main.lua file
print(sum_from_python(2,3))
Sounds like Lunatic-Python does exactly what you're looking for. 听起来像Lunatic-Python正是你正在寻找的。 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. 至于lupa,请注意它只是一个python模块 ,这意味着你必须使用python作为宿主语言 - 它不支持lua是“驱动”语言的用例。 For example, you won't be able to use lupa from a lua interpreter or from a C/C++ application that embeds lua.
例如,您将无法使用lua解释器中的lupa或嵌入lua的C / C ++应用程序。 OTOH, Lunatic-Python can be driven from either side of the bridge.
OTOH,Lunatic-Python可以从桥的任何一侧驱动。
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. 不要这样做:我同意其他人的建议,你应该找到一种方法在纯Lua中做到这一点,但也许你真的需要整合这两者。
You could use SWIG (www.swig.org) to export the Lua C API to Python. 您可以使用SWIG(www.swig.org)将Lua C API导出到Python。 You might save yourself some time by using a C++ binding (like lua-icxx.sf.net) but that really depends on your requirements.
您可以通过使用C ++绑定(如lua-icxx.sf.net)节省一些时间,但这实际上取决于您的要求。
You could use an existing library; 您可以使用现有的库; lunatic python is dead AFAIK, but LUPA seems in good health ( https://pypi.python.org/pypi/lupa ).
疯狂的蟒蛇死了AFAIK,但LUPA看起来身体健康( https://pypi.python.org/pypi/lupa )。
您可以尝试使用此库或编写一些特定于您的项目的桥接器,但需要熟悉Lua C-API和Python C-API。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.