Kenneth Falck's Blog

Embed parallel Lua states in Python

Posted on 2011-10-31 by Kenneth Falck

Lua is a popular embedded scripting language used by many tools and games such as World of Warcraft. There is also a Python port called Lunatic-Python. It wraps around liblua (the C library) and allows you to execute Lua code in Python and Python code in Lua.

I've created a fork of Lunatic-Python in:

This fork allows you to create multiple Lua states, each of which has its own set of global variables.

Previously, in Python you would execute Lua with a global state like this:

import lua
lua.globals()['msg'] = {'hello':'world'}

Now you can create multiple independent states using the new_state() function:

import lua
s1 = lua.new_state()
s2 = lua.new_state()
s1.globals()['msg'] = {'hello':'world'}
s2.globals()['msg'] = {'hello':'foobar'}

The purpose of this is that you can safely create a new, clean state when you're executing Lua in a Python function, and you don't have to worry about the global state overlapping with some other function or thread.

Please consider this fork experimental for now. It passes the tests but it may still contain memory leaks or other problems. Also, I have not tested it for embedding Python into Lua at all.