Skip to content

Call python function from lua #68

Description

@Martmists-GH

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

Activity

  1. greatwolf commented on May 29, 2019

    @greatwolf
    Collaborator

    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
    
  2. Martmists-GH commented on May 29, 2019

    @Martmists-GH
    Author

    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

  3. greatwolf commented on May 30, 2019

    @greatwolf
    Collaborator

    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?

  4. Martmists-GH commented on May 30, 2019

    @Martmists-GH
    Author

    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)

  5. greatwolf commented on May 30, 2019

    @greatwolf
    Collaborator

    What does it show when you print(my_lib)?

  6. m32 commented on Jun 3, 2026

    @m32

    @Martmists-GH sys.path does not include current directory

    py = require "python"
    py.execute "import sys; sys.path.insert(1, '.')"
    ....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions