Open Source

Luaj - Lua vm written in Java

prev next

How small can a lua interpreter be if it's written in Java?

Turns out less than 25 KB of obfuscated code.

In order to deal with some difficult situations presented by J2ME, like no ClassLoader, some of us were wondering how feasible it would be to build a byte code interpreter in Java for some other language. We soon settled on Lua and set about building a VM.

We managed to build a solid vm, and followed that with implementations of the standard libraries (50 KB), and finally ported the compiler (25 KB), so any valid lua script can be run on it. A debug library rounds out the picture for another 25 KB or so.

Currently, I am the primary committer at the luaj project hosted on SourceForge and also available on LuaForge. Version 2.0 is a significant rewrite whose implementation leverages the Java stack instead of a separate lua stack, and can be used with or without an actual lua bytecode interpreter. In this model the lua bytecode can be compiled directly into Java bytecode, lua source can be turned into Java source, lua bytecode can be interpreted, or all techniques can be mixed and matched depending the needs of the host runtime.

By using javacc and providing a new javacc grammar description, I was able to create a lua-bytecode to java-bytecode compiler that produces bytecode that outperforms the standard C lua interpreter for some of the computer language shootout benchmarks. It also bypasses the overhead of the full Java compiler, so is suitable for dynamic script-to-bytecode compiling in most Java environments.

Naturally, the compiled bytecode includes support for closures, metatables, and all standard features of the lua language, even though the underlying Java runtime does not.

For more details see the luaj README on the luaforge website