LuaObfuscator

Deadeye Obfuscator

A Lua obfuscator with a bytecode virtual machine — written entirely in Lua.

Deadeye’s headline protection is VM-based virtualization: it compiles your functions into a custom, per-build-randomized bytecode and runs them under a hand-written interpreter emitted into the output. The original logic of a virtualized function no longer exists as code — it becomes opaque data executed by the VM. Around that, a chain of classic source-to-source passes hardens everything else, and the tool emits a single file that behaves identically to the original while being far harder to read, diff, decompile, or statically analyze.

The whole toolchain — lexer, parser, expression IR, the VM compiler/interpreter generator, and every transformation pass — is implemented 100% in pure Lua, with no external dependencies. The obfuscated output is likewise plain Lua (5.3+).

Intended for protecting your own Lua source (game scripts, anti-cheat logic, licensed tooling). Only obfuscate code you own or are authorized to modify.

Highlights

Requirements

Usage

  1. Put the script you want to obfuscate in Input/ (e.g. Input/testinput.lua).
  2. Point Config.lua at it and name the output:

    InputPath  = "testinput.lua"   -- relative to Input/
    OutputPath = "testresult.lua"  -- written to Output/
    
  3. Run from the project root:

    lua Main.lua                      # uses Config's InputPath / OutputPath
    lua Main.lua myscript.lua         # input under Input/, output -> Output/<default>
    lua Main.lua myscript.lua out.lua # explicit input and output names
    lua Main.lua --help               # usage
    

    Positional arguments override InputPath/OutputPath; a value containing a path separator is used as-is instead of being resolved under Input//Output/.

The obfuscated file is written to Output/<OutputPath>. Set Config.Debug = true to also dump the intermediate stages (Output/after_emit.lua, Output/preminify.lua) when debugging a pass; they are off by default because they are near-plaintext snapshots.

Web UI (run it in your browser)

Prefer not to edit Config.lua by hand? The project ships a static web front-end in web/ that runs the real obfuscator entirely in your browser via Fengari (Lua 5.3 compiled to JavaScript), inside a Web Worker. Nothing is uploaded — obfuscation happens client-side — and the output is the same ordinary native Lua 5.3+ that lua Main.lua produces.

It exposes every setting interactively: the max/fast presets, per-pass toggles, the virtualization options (VirtualizePrefix, VirtualizeAll, VMLightweight), tuning sliders (variable-name length, dead-code probability, junk-pool ratio), save / load / export of named presets, a live estimated output cost meter, a streaming progress bar plus the full build log, multi-file input (file picker or drag-and-drop), and one-click download. Each build uses a fresh random seed automatically.

Self-host on localhost

The page must be served over HTTP — opening index.html directly via file:// won’t work, because it fetches the Lua modules and loads Fengari from a CDN. A tiny zero-dependency dev server is included:

python3 web/serve.py          # serves http://localhost:8000
python3 web/serve.py 8080     # pick another port

serve.py serves the web/ directory and maps /modules/*.lua to the repo-root .lua sources, so the local URL layout matches a real deployment. Open the printed URL, drop in a .lua file (or use Input/testinput.lua), choose a preset, and click Obfuscate — the result previews on the page and downloads as a normal .lua file.

Fengari interprets Lua in JavaScript, so a heavy build (e.g. VirtualizeAll on a large file) takes longer than native lua; the Web Worker keeps the UI responsive and the progress bar shows where it’s at. The produced file is byte-for-byte the kind of output the CLI makes.

To publish it as a shareable static site (e.g. GitHub Pages), see web/README.md: a GitHub Actions workflow (.github/workflows/pages.yml) assembles the app together with the .lua sources and deploys it.

Virtualization (the VM)

Any top-level global function whose name begins with Config.VirtualizePrefix (default "vm_") is compiled to the VM instead of being emitted as Lua. For example:

function vm_check(key)        -- compiled to bytecode + interpreter
    return hash(key) == SECRET
end

becomes, in the output, roughly vm_check = <interp>(<encrypted bytecode blob>) — the arithmetic, comparisons, and the constant SECRET no longer appear as source (or in the compiled bytecode’s constant table). Set Config.VirtualizePrefix = nil (or "") to disable prefix-based selection.

Selecting what to virtualize:

Supported in virtualized functions: arithmetic / logic / comparison / concat / length / unary ops, locals and globals, if/elseif/else, while, numeric and generic for, repeat, break, goto/labels’ callers, tables (including trailing ...), multiple return values, varargs (..., select), method / cross / recursive calls, nested functions, and closures with shared mutable upvalues. Coroutines (yield/resume) work through virtualized code.

Graceful fallback: anything the compiler can’t yet handle makes that one function stay native (compiled under pcall), so virtualization never produces broken output — it just protects less.

Transformation passes

Beyond the VM, each pass is a standalone module. They run in a fixed pipeline (Main.lua:Obfuscate): AST passes first, then text passes on the emitted source.

Pass Module What it does
Comment removal CommentRemover.lua Strips line/block comments without touching string literals.
Virtualization vm/*.lua Compiles vm_-prefixed functions to the bytecode VM (see above).
Dead code injection DeadCodeInjector.lua Inserts junk locals and never-taken blocks guarded by runtime opaque predicates.
Variable renaming VariableRenamer.lua Scope-aware renaming of locals to random _xxxx names; runs twice.
Control-flow flattening ControlFlowFlattening.lua Lowers statement blocks into dispatch state machines (handles return/break via a sentinel protocol).
Integer obfuscation NumericalObfuscator.lua Replaces numeric literals with hex, XOR closures, multiply/add chains, load-based expressions, and mixed-boolean-arithmetic identities.
String obfuscation LexicalObfuscator.lua Encodes string literals as self-decoding XOR closures, decoded once into a chunk-level pool. Each decode is also bound to a per-build seed computed by a runtime loop (not a literal), so no single decode expression can be constant-folded in isolation — an automated/LLM deobfuscator must evaluate the shared seed to recover any string.
String splitting StringSplitter.lua Breaks literals into concatenated fragments on escape-safe boundaries.
Constant pooling ConstantPooling.lua Collects constants into a shuffled pool table padded with junk, rewriting references through it.
Minification Minify.lua Collapses whitespace and tightens operators into a single line.
Anti-tamper Utils.lua Environment check, then an integrity-bound loader: the payload is encrypted and its decryption key is derived from a checksum of the ciphertext, so editing any byte (or stripping the check) yields the wrong key and the payload fails to load. The loader runs last (after every pass), so it is hardened by hand: the FNV/LCG hash and cipher constants are emitted as split arithmetic (not greppable magic numbers), the byte-extract is written arithmetically rather than as a bit-shift, and load is fetched indirectly so there is no literal load( sink to strip in one edit. Key material is stored split, not as a plaintext constant. One-time cost at startup; no runtime overhead. This is tamper-evidence, not secrecy — a determined attacker who executes the loader can still recover the plaintext; it defeats casual, automated, and one-shot-LLM deobfuscation.

An expression IR (ExprAST.lua) reconstructs a real tree from the parser’s token lists; it backs the VM compiler and a precedence-aware emitter.

The random seed is drawn from a crypto RNG where available (GenerateSecureSeed), or pin it with RandomSeed for reproducible output.

Configuration

All knobs live in Config.lua:

Setting Default Meaning
InputPath "testinput.lua" Source file inside Input/.
OutputPath "testresult.lua" Result file inside Output/.
VariableLength 12 Length of generated variable names.
DeadCodeInjectProbability 0.45 Chance (0.0–1.0) of injecting a dead block before each statement.
JunkPoolRatioMin / JunkPoolRatioMax 50 / 100 Percentage range of junk entries added to the constant pool.
RandomSeed nil Set a number to force a fixed seed for reproducible output.
Config.VirtualizePrefix "vm_" Name prefix selecting top-level functions to virtualize; nil/"" disables prefix-based selection.
Config.VirtualizeAll false When true, virtualize every eligible top-level function (prefix ignored); ineligible functions safely stay native. Maximum coverage, higher runtime cost.
Config.VirtualizeNames nil Optional allow-list of exact function names to virtualize without renaming them to the prefix, e.g. {"checkLicense","validate"} (array or set).
Config.CamouflageNames true Generated identifiers use randomized length + mixed case with no fixed _ prefix, so they don’t all match one _[a-z0-9]{N} regex a deobfuscator could use to spot obfuscated names. Set false for the old fixed-shape names.
Config.Debug false When true, also writes intermediate build artifacts (Output/after_emit.lua, Output/preminify.lua). Off by default — those are near-plaintext/partly-obfuscated snapshots.
Config.VMLightweight true Exempt the spliced VM interpreter from dead-code injection and control-flow flattening (renaming and the text passes still apply to it). Large speedup (~70× on a VM-heavy loop) and much smaller output for virtualized code, with no change to how your own code is obfuscated; only the interpreter becomes slightly easier to pattern-match (opcodes still permuted, constants still encrypted per build). Default true; set false to also flatten/junk the engine itself.
Config.Preset "max" Strength preset that seeds Config.Passes: "max" (every pass on, strongest, slowest) or "fast" (performance mode — see below).
Config.Passes.* from preset Per-pass on/off switches (CommentRemoval, DeadCode, Rename, Flatten, NumberObf, StringObf, StringSplit, ConstantPool, Minify, AntiTamper). Seeded from Config.Preset; override any individual pass after the preset line.

Performance modes

Virtualized code runs under an interpreter, so it is inherently slower than native Lua — the VM is the right tool for the handful of functions that are worth protecting, not for hot loops. Two presets trade strength against speed:

Separately, string obfuscation is decode-once: each distinct string literal is encoded a single time into a chunk-level pool that is built when the program loads, and every use becomes a cheap table access. A string used inside a hot loop is therefore decoded once at startup rather than re-decoded on every iteration — a large speedup with no change to the encoding or its strength. (Number obfuscation needs no such treatment: its expressions are constant folded by Lua at compile time, so they cost nothing per evaluation.)

Best practice for speed without losing protection: keep the default "max" preset but virtualize selectively — give only your license checks, key routines, and anti-cheat logic the vm_ prefix, and leave hot paths native. That concentrates the expensive VM where it matters. Pair it with Config.VMLightweight = true to drop the interpreter’s own overhead without touching how your code is obfuscated. (The interpreter is also tuned so the per-build number-obfuscation pass no longer rewrites its hot-path constants — a large speedup over naive virtualization with no loss of strength.)

Testing

run_tests.lua is a round-trip harness: for every fixture it runs the original and the obfuscated output and compares stdout + exit status, so a regression in any pass shows up immediately.

lua run_tests.lua
# or point it at a specific interpreter:
LUA_BIN=/path/to/lua lua run_tests.lua
# also validate the expression-IR emit path:
USE_EXPR_AST=1 lua run_tests.lua
# stress mode: virtualize every eligible function in every fixture:
VIRTUALIZE_ALL=1 lua run_tests.lua
# validate a strength preset across the suite:
PRESET=fast lua run_tests.lua
# multi-seed fuzz: obfuscate each fixture under N pinned seeds (catches
# probabilistic bugs in the per-build-randomized passes):
FUZZ=20 lua run_tests.lua
# validate Lua 5.4-only fixtures (<const>/<close>) against a 5.4 interpreter:
LUA_BIN_54=/path/to/lua5.4 lua run_tests.lua

Fixtures live in test/fixtures/ and cover closures, varargs, metatables, coroutines, goto, bitwise ops, control-flow edge cases, the VM feature set, and targeted regression cases (hex floats, 5.4 attributes, tricky string literals, function-literal returns inside flattened blocks).

A separate harness, security_check.lua, asserts the output’s security properties rather than behavior: that a known plaintext/numeric secret never survives in the output, that the program still produces it at runtime, and that flipping bytes in the anti-tamper payload breaks execution (the secret never leaks from a tampered file).

lua security_check.lua

Project layout

Main.lua              -- entry point; drives Obfuscate()
Config.lua            -- all tunable settings
Libraries.lua         -- requires every module in order
Reader.lua            -- file input
Lexer.lua / Parser.lua / Emitter.lua   -- tokenize -> AST -> source
ExprAST.lua           -- expression IR (tree from token lists + precedence-aware emit)
vm/                   -- bytecode VM: Opcodes, Compiler, Interp, Serializer, Virtualize
*Obfuscator / *Splitter / *Pooling ... -- the transformation passes
Utils.lua             -- shared helpers (seed, random names, anti-tamper)
run_tests.lua         -- round-trip correctness harness
test/fixtures/        -- harness inputs
Input/                -- source files to obfuscate
Output/               -- results + intermediate dumps (after_emit, preminify)
web/                   -- browser front-end (static site + serve.py dev server; runs the obfuscator via Fengari)
.github/workflows/     -- GitHub Pages deploy for the web UI

License

MIT — see LICENSE. Copyright (c) 2026 Pharell Jay Jeyakumar.