MoonPie - Lua Interpreter in Python
A Lua interpreter written in Python, implementing core Lua language features.
Installation
Requires Python 3.11 or newer.
From PyPI (when published)
pip install moonpie
From Source
git clone https://github.com/rhulha/MoonPie.git
cd MoonPie
pip install -e .
Features
Language Support
- Data Types: nil, booleans, numbers, strings, tables, functions
- Operators: arithmetic (
+ - * / // % ^), comparison (== ~= < <= > >=, numbers and strings), logical (and or not, short-circuit), concatenation (..), length (#) - Variables: local and global, with proper block scoping and a fresh loop variable per iteration
- Assignment: multiple assignment (
a, b = b, a) and multiple return values - Functions: closures, varargs (
...), methods (obj:method()),function a.b.c:m()definitions,f"str"/f{...}call syntax - Control Flow: if/elseif/else, while, repeat-until, numeric for, generic for (
pairs,ipairs, custom iterators), break - Metatables:
__index,__newindex,__call,__tostring, arithmetic,__concat,__eq,__lt,__le,__len,__unm,__pairs - Literals: decimal, exponent and hex numbers (
1e3,0xFF,0x1p4), long strings and comments ([[...]],[==[...]==]), all string escapes - Errors: Lua-style messages with
file:line:positions;error,pcall,xpcall
Built-in Functions
- Basic: print, type, tostring, tonumber, assert, error, pcall, xpcall, select, next, pairs, ipairs, unpack, setmetatable, getmetatable, rawget, rawset, rawequal, rawlen, _G
- Math: abs, floor, ceil, sqrt, sin, cos, tan, max, min, pi, huge
- String: len, upper, lower, sub, rep, format, find, match, gmatch, gsub (strings also support
s:method()) - Table: insert, remove, concat, sort, unpack
- IO: write
Architecture
The interpreter follows a classic architecture:
- Lexer (
lexer.py) - Tokenizes Lua source code - Parser (
parser.py) - Builds an Abstract Syntax Tree (AST) from tokens - AST Nodes (
ast_nodes.py) - Defines all AST node types - Evaluator (
evaluator.py) - Traverses and executes the AST - Object System (
lua_object.py) - Lua tables, functions and value helpers - Built-ins (
lua_builtins.py) - Provides standard Lua functions - Patterns (
lua_patterns.py) - Translates Lua patterns to Python regular expressions
Usage
Command Line (after installation)
moonpie # Start interactive REPL
moonpie script.lua # Execute a Lua file
moonpie examples/examples.lua
Python Module
python -m moonpie # Start interactive REPL
python -m moonpie script.lua
As a Library
from moonpie import LuaInterpreter, LuaError
interpreter = LuaInterpreter()
results = interpreter.run("""
function add(a, b)
return a + b
end
print(add(5, 3))
return add(1, 2), "done"
""")
print(results) # [3.0, 'done']
try:
interpreter.run("error('boom')")
except LuaError as e:
print(e) # input:1: boom
run returns the values returned by the chunk as a list and raises LuaError
(or LuaSyntaxError) on errors. Lua values map to Python as nil -> None,
booleans -> bool, numbers -> float, strings -> str; tables are LuaTable.
Example Code
-- Variables and arithmetic
local x = 10
local y = 20
print(x + y) -- 30
-- Functions
function factorial(n)
if n <= 1 then
return 1
else
return n * factorial(n - 1)
end
end
print(factorial(5)) -- 120
-- Tables
local person = {name = "John", age = 30}
print(person.name) -- John
local array = {10, 20, 30}
print(array[1]) -- 10
print(#array) -- 3
-- Loops
for i = 1, 5 do
print(i)
end
-- String operations
local greeting = "Hello" .. " " .. "World"
print(greeting) -- Hello World
Testing
Run the test suite:
pip install pytest
python -m pytest tests
Run examples:
moonpie examples/examples.lua
Implementation Details
- Lexer: Tokenizes keywords, operators, numbers, short and long strings, and comments
- Parser: Recursive descent parser using Lua 5.4 operator priorities
- Evaluator: Tree-walking interpreter with lexical scopes and metatable-aware operations
- Numbers: All numbers are floats (as in Lua 5.1) and print with
%.14g - Recursion: Up to about 7000 nested Lua calls, then a catchable "stack overflow" error
Limitations
This is a Lua interpreter for educational purposes. Not implemented:
- Coroutines,
gotoand labels - Integer subtype and bitwise operators (Lua 5.3+)
require,load, file I/O,oslibrary, and most ofio%bin string patterns- Proper tail calls
- Strings are Python (Unicode) strings, so
#counts characters, not bytes
References
Metadata
Release files for moonpie 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| moonpie-0.2.0.tar.gz | 31.4 kB | Without provenance | Details for moonpie-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| moonpie-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for moonpie-0.2.0-py3-none-any.whl |
Total release size: 58.1 kB
Release files / moonpie-0.2.0.tar.gz
| Download URL | moonpie-0.2.0.tar.gz |
|---|---|
| Size | 31.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
3ac7b9a5a1d3871c919a3aa5bf9cac984ac997566b15c147d75ebdd316a0f79d
|
|
BLAKE2b-256 checksum How to use checksums |
202539fea71d26fe733bb62616b733dea0ff3b9c39db80c050569f697dc80267
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.10
|
Release files / moonpie-0.2.0-py3-none-any.whl
| Download URL | moonpie-0.2.0-py3-none-any.whl |
|---|---|
| Size | 26.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2bda56721da4cef10698d2074017002704c4e76d29c7d255e773d88b1b2fa1b4
|
|
BLAKE2b-256 checksum How to use checksums |
76434b203c23cfbf01173caadf6eae51ac9f90ede26f3f3e5e75b70265f58209
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.10
|
Security for moonpie 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.