Lupa: Python Wrapper around Lua and LuaJIT

2.6 · active · verified Sun Mar 29

Lupa is a Python library that seamlessly integrates the runtimes of Lua or LuaJIT2 into CPython. It enables Python developers to embed Lua code, call Lua functions from Python, and interact with Python objects from within Lua. Key features include separate Lua runtime states, Python coroutine wrappers for Lua coroutines, and robust iteration support between the two languages. Currently at version 2.6, Lupa is actively maintained, with releases focusing on cross-version compatibility and feature enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic interoperability: creating a Lua runtime, evaluating Lua code, defining and calling Lua functions from Python, and exposing Python functions and builtins to the Lua environment.

import os
from lupa import LuaRuntime

# Create a Lua runtime instance
lua = LuaRuntime(unpack_returned_tuples=True)

# Evaluate Lua code directly
result_eval = lua.eval('1 + 2')
print(f'Lua eval("1 + 2"): {result_eval}')

# Define a Lua function and call it from Python
lua_add_func = lua.eval('function(x, y) return x + y end')
result_lua_call = lua_add_func(5, 7)
print(f'Called Lua function (5, 7): {result_lua_call}')

# Pass a Python function into Lua and call it
def py_multiply(a, b):
    return a * b

lua.globals().py_multiply = py_multiply
result_python_call_from_lua = lua.eval('py_multiply(3, 4)')
print(f'Called Python function from Lua (3, 4): {result_python_call_from_lua}')

# Access Python builtins from Lua
python_str_from_lua = lua.eval('python.builtins.str(123)')
print(f'Python str from Lua: {python_str_from_lua}')

view raw JSON →