Skip to main content

Python wrapper around LuaJIT

Project description

Lupa

Lupa integrates the LuaJIT2 runtime into CPython. It is a partial rewrite of LunaticPython in Cython with some additional features such as proper coroutine support.

Major features

  • separate Lua runtime states through a LuaRuntime class

  • Python coroutine wrapper for Lua coroutines

  • proper encoding and decoding of strings (configurable per runtime, UTF-8 by default)

  • frees the GIL and supports threading in separate runtimes when calling into Lua

  • supports Python 2.x and 3.x, potentially starting with Python 2.3 (currently untested)

  • written for LuaJIT2, as opposed to the Lua interpreter (tested with LuaJIT 2.0.0-beta4)

  • easy to hack on and extend as it is written in Cython, not C

Why use it?

It complements Python very well. Lua is a language as dynamic as Python, but LuaJIT compiles it to very fast machine code, sometimes faster than many other compiled languages. The language runtime is extremely small and carefully designed for embedding. The complete binary module of Lupa, including a statically linked LuaJIT2 runtime, is only some 500KB on a 64 bit machine.

However, Lua code is harder to write than Python code as the language lacks most of the batteries that Python includes. Writing large programs in Lua is rather futile, but it provides a perfect backup language when raw speed is more important than simplicity, and edit-compile-run cycles are too heavy for agile development.

Lupa is a very fast and thin wrapper around LuaJIT. It makes it easy to write dynamic Lua code that accompanies dynamic Python code by switching between the two languages at runtime, based on the tradeoff between simplicity and speed.

Examples

>>> import lupa
>>> from lupa import LuaRuntime
>>> lua = LuaRuntime()

>>> lua.eval('1+1')
2

>>> lua_func = lua.eval('function(f, n) return f(n) end')

>>> def py_add1(n): return n+1
>>> lua_func(py_add1, 2)
3

>>> lua.eval('python.eval(" 2 ** 2 ")') == 4
True
>>> lua.eval('python.builtins.str(4)') == '4'
True

Python objects in Lua

Python objects are either converted when passed into Lua (e.g. numbers and strings) or passed as wrapped object references.

>>> lua_type = lua.globals().type   # Lua's type() function
>>> lua_type(1) == 'number'
True
>>> lua_type('abc') == 'string'
True

Wrapped Lua objects get unwrapped when they are passed back into Lua, and arbitrary Python objects get wrapped in different ways:

>>> lua_type(lua_type) == 'function'  # unwrapped Lua function
True
>>> lua_type(eval) == 'function'      # wrapped Python function
True
>>> lua_type([]) == 'userdata'        # wrapped Python object
True

Lua supports two main protocols on objects: calling and indexing. It does not distinguish between attribute access and item access like Python does, so the Lua operations obj[x] and obj.x both map to indexing. To decide which Python protocol to use for Lua wrapped objects, Lupa employs a simple heuristic.

Pratically all Python objects allow attribute access, so if the object also has a __getitem__ method, it is preferred when turning it into an indexable Lua object. Otherwise, it becomes a simple object that uses attribute access for indexing from inside Lua. Additionally, if the object is callable, it turns into a Lua function.

Obviously, this heuristic will fail to provide the required behaviour in many cases, e.g. when attribute access is required to an object that happens to support item access. To be explicit about the protocol that should be used, Lupa provides the helper functions as_attrgetter() and as_itemgetter() that restrict the view on an object to a certain protocol, both from Python and from inside Lua:

>>> lua_func = lua.eval('function(obj) return obj["get"] end')
>>> lua_func({'get' : 'got'}) == 'got'
True
>>> dict_get = lua_func( lupa.as_attrgetter({'get' : 'got'}) )
>>> dict_get('get') == 'got'
True

>>> lua_func = lua.eval(
...     'function(obj) return python.as_attrgetter(obj)["get"] end')
>>> dict_get = lua_func({'get' : 'got'})
>>> dict_get('get') == 'got'
True

Lua code can also use the as_function() function to make a Python object callable from Lua that was not wrapped as a function at the Python-to-Lua border.

>>> lua_func = lua.eval(
...     'function(obj) return obj(1,2,3) end')
>>> lua_func({})
Traceback (most recent call last):
TypeError: 'dict' object is not callable
>>> lua_func = lua.eval(
...     'function(obj) return python.as_function(obj)(1,2,3) end')
>>> lua_func({})
Traceback (most recent call last):
TypeError: 'dict' object is not callable

>>> def py_func(): pass
>>> lua_func = lua.eval('function(obj) return python.as_function(obj) end')
>>> py_func == lua_func(py_func)
True

Note that Python objects wrapped as functions are still indexable:

>>> lua_func = lua.eval(
...     'function(obj) return python.as_function(obj)["get"] end')
>>> lua_func({'get' : 'got'}) == 'got'
True

>>> def py_func(): pass
>>> py_func.ATTR = 2
>>> lua_func = lua.eval('function(obj) return obj.ATTR end')
>>> lua_func(py_func)
2
>>> lua_func = lua.eval(
...     'function(obj) return python.as_attrgetter(obj).ATTR end')
>>> lua_func(py_func)
2
>>> lua_func = lua.eval(
...     'function(obj) return python.as_attrgetter(obj)["ATTR"] end')
>>> lua_func(py_func)
2

Lua Tables

Lua tables mimic Python’s mapping protocol. For the special case of array tables, Lua automatically inserts integer indices as keys into the table. Therefore, indexing starts from 1 as in Lua instead of 0 as in Python. For the same reason, negative indexing does not work. It is best to think of Lua tables as mappings rather than arrays, even for plain array tables.

>>> table = lua.eval('{10,20,30,40}')
>>> table[1]
10
>>> table[4]
40
>>> list(table)
[1, 2, 3, 4]
>>> list(table.values())
[10, 20, 30, 40]
>>> len(table)
4

>>> mapping = lua.eval('{ [1] = -1 }')
>>> list(mapping)
[1]

>>> mapping = lua.eval('{ [20] = -20; [3] = -3 }')
>>> mapping[20]
-20
>>> mapping[3]
-3
>>> sorted(mapping.values())
[-20, -3]
>>> sorted(mapping.items())
[(3, -3), (20, -20)]

>>> mapping[-3] = 3     # -3 used as key, not index!
>>> mapping[-3]
3
>>> sorted(mapping)
[-3, 3, 20]
>>> sorted(mapping.items())
[(-3, 3), (3, -3), (20, -20)]

A lookup of nonexisting keys or indices returns None (actually nil inside of Lua). A lookup is therefore more similar to the .get() method of Python dicts than to a mapping lookup in Python.

>>> table[1000000] is None
True
>>> table['no such key'] is None
True
>>> mapping['no such key'] is None
True

Note that len() does the right thing for array tables but does not work on mappings:

>>> len(table)
4
>>> len(mapping)
0

This is because len() is based on the # (length) operator in Lua and because of the way Lua defines the length of a table. Remember that unset table indices always return nil, including indices outside of the table size. Thus, Lua basically looks for an index that returns nil and returns the index before that. This works well for array tables that do not contain nil values, gives barely predictable results for tables with ‘holes’ and does not work at all for mapping tables. For tables with both sequential and mapping content, this ignores the mapping part completely.

Note that it is best not to rely on the behaviour of len() for mappings. It might change in a later version of Lupa.

Similar to the table interface provided by Lua, Lupa also supports attribute access to table members:

>>> table = lua.eval('{ a=1, b=2 }')
>>> table.a, table.b
(1, 2)
>>> table.a == table['a']
True

This enables access to Lua ‘methods’ that are associated with a table, as used by the standard library modules:

>>> string = lua.eval('string')    # get the 'string' library table
>>> print( string.lower('A') )
a

Lua Coroutines

The next is an example of Lua coroutines. A wrapped Lua coroutine behaves exactly like a Python coroutine. It needs to get created at the beginning, either by using the .coroutine() method of a function or by creating it in Lua code. Then, values can be sent into it using the .send() method or it can be iterated over. Note that the .throw() method is not supported, though.

>>> lua_code = '''\
...     function(N)
...         for i=0,N do
...             coroutine.yield( i%2 )
...         end
...     end
... '''
>>> lua = LuaRuntime()
>>> f = lua.eval(lua_code)

>>> gen = f.coroutine(4)
>>> list(enumerate(gen))
[(0, 0), (1, 1), (2, 0), (3, 1), (4, 0)]

An example where values are passed into the coroutine using its .send() method:

>>> lua_code = '''\
...     function()
...         local t,i = {},0
...         local value = coroutine.yield()
...         while value do
...             t[i] = value
...             i = i + 1
...             value = coroutine.yield()
...         end
...         return t
...     end
... '''
>>> f = lua.eval(lua_code)

>>> co = f.coroutine()   # create coroutine
>>> co.send(None)        # start coroutine (stops at first yield)

>>> for i in range(3):
...     co.send(i*2)

>>> mapping = co.send(None)   # loop termination signal
>>> list(mapping.items())
[(0, 0), (1, 2), (2, 4)]

It also works to create coroutines in Lua and to pass them back into Python space:

>>> lua_code = '''\
...   function f(N)
...         for i=0,N do
...             coroutine.yield( i%2 )
...         end
...   end ;
...   co1 = coroutine.create(f) ;
...   co2 = coroutine.create(f) ;
...
...   status, first_result = coroutine.resume(co2, 2) ;   -- starting!
...
...   return f, co1, co2, status, first_result
... '''

>>> lua = LuaRuntime()
>>> f, co, lua_gen, status, first_result = lua.execute(lua_code)

>>> # a running coroutine:

>>> status
True
>>> first_result
0
>>> list(lua_gen)
[1, 0]
>>> list(lua_gen)
[]

>>> # an uninitialised coroutine:

>>> gen = co(4)
>>> list(enumerate(gen))
[(0, 0), (1, 1), (2, 0), (3, 1), (4, 0)]

>>> gen = co(2)
>>> list(enumerate(gen))
[(0, 0), (1, 1), (2, 0)]

>>> # a plain function:

>>> gen = f.coroutine(4)
>>> list(enumerate(gen))
[(0, 0), (1, 1), (2, 0), (3, 1), (4, 0)]

Threading

The following example calculates a mandelbrot image in parallel threads and displays the result in PIL. It is based on a benchmark implementation for the Computer Language Benchmarks Game.

lua_code = '''\
    function(N, i, total)
        local char, unpack = string.char, unpack
        local result = ""
        local M, ba, bb, buf = 2/N, 2^(N%8+1)-1, 2^(8-N%8), {}
        local start_line, end_line = N/total * (i-1), N/total * i - 1
        for y=start_line,end_line do
            local Ci, b, p = y*M-1, 1, 0
            for x=0,N-1 do
                local Cr = x*M-1.5
                local Zr, Zi, Zrq, Ziq = Cr, Ci, Cr*Cr, Ci*Ci
                b = b + b
                for i=1,49 do
                    Zi = Zr*Zi*2 + Ci
                    Zr = Zrq-Ziq + Cr
                    Ziq = Zi*Zi
                    Zrq = Zr*Zr
                    if Zrq+Ziq > 4.0 then b = b + 1; break; end
                end
                if b >= 256 then p = p + 1; buf[p] = 511 - b; b = 1; end
            end
            if b ~= 1 then p = p + 1; buf[p] = (ba-b)*bb; end
            result = result .. char(unpack(buf, 1, p))
        end
        return result
    end
'''

image_size = 1280   # == 1280 x 1280
thread_count = 8

from lupa import LuaRuntime
lua_funcs = [ LuaRuntime(encoding=None).eval(lua_code)
              for _ in range(thread_count) ]

results = [None] * thread_count
def mandelbrot(i, lua_func):
    results[i] = lua_func(image_size, i+1, thread_count)

import threading
threads = [ threading.Thread(target=mandelbrot, args=(i,lua_func))
            for i, lua_func in enumerate(lua_funcs) ]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()

result_buffer = b''.join(results)

# use PIL to display the image
import Image
image = Image.fromstring('1', (image_size, image_size), result_buffer)
image.show()

Note how the example creates a separate LuaRuntime for each thread to enable parallel execution. Each LuaRuntime is protected by a global lock that prevents concurrent access to it. The low memory footprint of Lua makes it reasonable to use multiple runtimes, but this setup also means that values cannot easily be exchanged between threads inside of Lua. They must either get copied through Python space (passing table references will not work, either) or use some Lua mechanism for explicit communication, such as a pipe or some kind of shared memory setup.

Installing lupa

  1. Download and unpack lupa

    http://pypi.python.org/pypi/lupa

  2. Download LuaJIT2

    http://luajit.org/download.html

  3. Unpack the archive into the lupa base directory, e.g.:

    .../lupa-0.1/LuaJIT-2.0.0-beta4
  4. Build LuaJIT:

    cd LuaJIT-2.0.0-beta4
    make
    cd ..

    If you need specific C compiler flags, pass them to make as follows:

    make CFLAGS="..."
  5. Build lupa:

    python setup.py build

Lupa change log

0.13.1 (2010-08-30)

  • fix Cython generated C file using Cython 0.13

0.13 (2010-08-29)

  • fixed undefined behaviour on str(lua_object) when the object’s __tostring() meta method fails

  • removed redundant “error:” prefix from LuaError messages

  • access to Python’s python.builtins from Lua code

  • more generic wrapping rules for Python objects based on supported protocols (callable, getitem, getattr)

  • new helper functions as_attrgetter() and as_itemgetter() to specify the Python object protocol used by Lua indexing when wrapping Python objects in Python code

  • new helper functions python.as_attrgetter(), python.as_itemgetter() and python.as_function() to specify the Python object protocol used by Lua indexing of Python objects in Lua code

  • item and attribute access for Python objects from Lua code

0.12 (2010-08-16)

  • fix Lua stack leak during table iteration

  • fix lost Lua object reference after iteration

0.11 (2010-08-07)

  • error reporting on Lua syntax errors failed to clean up the stack so that errors could leak into the next Lua run

  • Lua error messages were not properly decoded

0.10 (2010-07-27)

0.9 (2010-07-23)

  • fixed Python special double-underscore method access on LuaObject instances

  • Lua coroutine support through dedicated wrapper classes, including Python iteration support. In Python space, Lua coroutines behave exactly like Python generators.

0.8 (2010-07-21)

  • support for returning multiple values from Lua evaluation

  • repr() support for Lua objects

  • LuaRuntime.table() method for creating Lua tables from Python space

  • encoding fix for str(LuaObject)

0.7 (2010-07-18)

  • LuaRuntime.require() and LuaRuntime.globals() methods

  • renamed LuaRuntime.run() to LuaRuntime.execute()

  • support for len(), setattr() and subscripting of Lua objects

  • provide all built-in Lua libraries in LuaRuntime, including support for library loading

  • fixed a thread locking issue

  • fix passing Lua objects back into the runtime from Python space

0.6 (2010-07-18)

  • Python iteration support for Lua objects (e.g. tables)

  • threading fixes

  • fix compile warnings

0.5 (2010-07-14)

  • explicit encoding options per LuaRuntime instance to decode/encode strings and Lua code

0.4 (2010-07-14)

  • attribute read access on Lua objects, e.g. to read Lua table values from Python

  • str() on Lua objects

  • include .hg repository in source downloads

  • added missing files to source distribution

0.3 (2010-07-13)

  • fix several threading issues

  • safely free the GIL when calling into Lua

0.2 (2010-07-13)

  • propagate Python exceptions through Lua calls

0.1 (2010-07-12)

  • first public release

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lupa-0.13.1.tar.gz (103.3 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page