Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a Python function from Lua?

Tags:

python

lua

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)) 
like image 628
Prashant Gaur Avatar asked Dec 05 '13 12:12

Prashant Gaur


2 Answers

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.

  1. It's not really thread-safe. Using the python threading library inside lua will have unexpected behavior.
  2. 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.
  3. 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.

like image 113
greatwolf Avatar answered Oct 24 '22 09:10

greatwolf


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).

like image 41
Oliver Avatar answered Oct 24 '22 10:10

Oliver