lunatic-python icon indicating copy to clipboard operation
lunatic-python copied to clipboard

Call python function from lua

Open Martmists-GH opened this issue 6 years ago • 5 comments

Is there a way to call a python function from Lua? I've tried the following:

-- main.lua
py = require "python"
my_lib = py.import "my_lib"
print(my_lib.test)  -- nil, so I can't call it.
# my_lib.py
def test():
    return 10

Martmists-GH avatar May 29 '19 17:05 Martmists-GH

The handle to the module is returned by py.import so you have to access it through that. For example

local py = require "python"
local mylib = py.import "my_lib"
print(mylib.test)
mylib.test()      --> should return 10.0

greatwolf avatar May 29 '19 18:05 greatwolf

when doing that I simply get

main.lua:4: attempt to call field 'test' (a nil value)

I'm using Lua 5.1 and Python 3.7, both x64

Martmists-GH avatar May 29 '19 22:05 Martmists-GH

I just tested this on Lua 5.3 with Python 3.3 32-bit but I can't reproduce the error. What's the lua and python script that's producing that error?

greatwolf avatar May 30 '19 04:05 greatwolf

Literally the code in my initial post is causing this. I don't think I modified any files before building either. (Aside from marking the luaopen_python as __declspec(dllexport) to export the function on windows)

Martmists-GH avatar May 30 '19 11:05 Martmists-GH

What does it show when you print(my_lib)?

greatwolf avatar May 30 '19 19:05 greatwolf