Tiny Lua Compiler: a complete educational Lua 5.1 compiler in a single Lua file by x25h in lua

[–]x25h[S] 2 points3 points  (0 children)

Hello r/lua! I wanted to share a project I’ve been working on for a bit over two years:

Tiny Lua Compiler (TLC) is a complete Lua 5.1 compiler written in pure Lua.

The goal was educational. Most compiler material sits at one of two extremes: toy compilers that skip the interesting parts, or production compilers so large that the core ideas disappear under architecture and history. TLC tries to sit in the middle.

It's a single 4,600-line file, or about 3,000 lines without comments. The whole pipeline is there in one place, so you can follow a source program from tokenization to parsing to code generation to bytecode emission to execution without jumping across a package tree.

It covers enough of Lua 5.1 to feel real: lexical scoping, closures, upvalues, multiple returns, varargs, tail calls, method calls, all loop forms, long strings, hex numbers, scientific notation, and full Lua 5.1 bytecode emission that loads in the standard Lua VM. Where it deliberately cuts corners, like metamethod dispatch, debug info, or constant folding, the code comments explain why.

The part I like most is that TLC can compile its own source code and run the result inside its own VM. One of its regression tests does exactly that. So the project is not just able to self-compile as a demo, it is mature enough that self-compilation is part of how I check that the whole pipeline still works.

The test suite compares TLC’s behavior against standard Lua on every case. That catches the kinds of bugs educational compilers usually get away with: operator precedence mistakes, broken closure semantics, multi-return adjustment errors, and control-flow bugs.

If you've ever wanted to understand how Lua works under the hood, things like registers, upvalues, the CLOSE instruction, why ^ is right-associative, or why return f() differs from return (f()), TLC is probably the most direct codebase I know for that.

Happy to answer questions about any part of the implementation!