python调用lua_如何从Lua调用Python函数?

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值