如何从Lua调用Python函数? [英] How to call a Python function from Lua?

查看:1558
本文介绍了如何从Lua调用Python函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的lua文件中运行python脚本.我该如何实现?

I want to run a python script from my lua file. How can I achieve this?

示例:

Python代码

#sum.py file
def sum_from_python(a,b)
    return a+b 

Lua代码

--main.lua file
print(sum_from_python(2,3)) 

推荐答案

像Lunatic-Python这样的声音确实可以满足您的需求.有一个 lunatic-python 的分支比原始版本更好.不久前,我已经为它修复了一些错误.

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

Lua代码:

-- main.lua
py = require 'python'

sum_from_python = py.import "sum".sum_from_python
print( sum_from_python(2,3) )

输出:

lua main.lua
5

大多数内容都可以按照您的预期工作,但是lunatic-python有一些限制.

Most of the stuff works as you would expect but there are a few limitations to lunatic-python.

  1. 这不是真正的线程安全.在lua内部使用python线程库会产生意外的行为.
  2. 无法通过lua的关键字参数调用python函数.一个想法是通过传递一个表在lua中模拟它,但是我从来没有实现它.
  3. 与lupa不同,lunatic-python仅具有一个全局lua状态和一个python VM上下文.因此,您不能使用lunatic-python创建多个VM运行时.

对于lupa,请注意,它只是一个 python模块,这意味着您必须使用python作为宿主语言-它不支持lua是驱动"的用例语言.例如,您将无法从lua解释器或嵌入lua的C/C ++应用程序中使用lupa. OTOH,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.

这篇关于如何从Lua调用Python函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆