📖 Learn Lua — Zero to Hero

A code-first, production-grade Lua curriculum. Every chapter is structured around annotated code blocks: complex implementations, anti-patterns with fixes, performance tips, edge cases, and debugging challenges. Minimal prose, maximum signal.

Lua is a lightweight, embeddable scripting language with a register-based VM, used in game engines (Roblox, Garry's Mod, Defold), configuration (Neovim, AwesomeWM), databases (Redis), networking (OpenResty, Nginx), and embedded systems. Its entire runtime is a C library — the lua executable is a 200-line wrapper.

How to Use This Course

  1. Read sequentially (01 → 16) for a structured path from runtime architecture to capstone projects.
  2. Jump to a chapter as a reference when you hit a concept in production.
  3. Run every code example — they're written as self-contained, executable scripts.
  4. Solve the Spot the Bug challenges before reading the answers.

Prerequisites

  • Lua 5.4+ installed (brew install lua / apt install lua5.4), or LuaJIT 2.1+.
  • luarocks for package management (brew install luarocks).
  • luacheck for linting (luarocks install luacheck).
  • Comfort with at least one other dynamic language (Python, JS, Ruby).

Curriculum

Part I — Foundations & Execution Model

#TopicWhy It Matters
01Runtime Architecture & ExecutionChunk compilation, load/loadfile/require pipeline, _G registry, sandboxing, hot-reload.
02Types, Scoping & Memory8-type system, integer/float duality, _ENV mechanics, upvalue cells, table reference semantics, weak tables.
03Functions, Closures & TCOFirst-class functions, MRV truncation rules, varargs with select/pack, proper tail calls, state machines.
04Control Flow & Iteratorsif as statement, numeric/generic for with the iterator protocol, table dispatch as switch, goto for state machines.

Part II — Tables & Data Structures

#TopicWhy It Matters
05Tables, OOP & Data StructuresArray/hash internals, reference vs value, shallow/deep copy with cycles, OOP via __index, mixins, linked list, ring buffer, object pool.
06Strings, Patterns & BinaryImmutable interned strings, Lua pattern engine (not regex), captures, frontier %f, UTF-8, string.byte/char for binary protocols.

Part III — Metaprogramming & Concurrency

#TopicWhy It Matters
07Metatables & MetamethodsFull metamethod reference, operator overloading, __index/__newindex proxies, read-only tables, __gc/__close for resources.
08Modules & Packagesrequire cache, package.searchers/preload, circular dependency resolution, hot-reload, dependency injection, luarocks.
11Coroutines & Generatorscreate/resume/yield protocol, stackful yielding, generators as iterators, producer-consumer pipelines, cooperative scheduler.

Part IV — Robustness & I/O

#TopicWhy It Matters
09Error Handlingerror levels, pcall/xpcall, structured errors with metatables, retry with backoff, circuit breaker, <close> cleanup.
10I/O, Files & BinaryFile handle lifecycle, streaming with :lines(), seek/tell, binary I/O, io.popen subprocess, atomic writes, CSV/INI parsers.

Part V — Standard Library & Performance

#TopicWhy It Matters
12Standard Library Deep-Divemath (random/precision/integer), os (time/date/env), table (sort/move/pack), debug (introspection/hooks), package (searchers/preload).
13Performance & LuaJITGlobal vs local cost, table rehash avoidance, table.concat vs .., closure allocation, collectgarbage profiling, LuaJIT FFI.

Part VI — Engineering & Capstone

#TopicWhy It Matters
14Testing & MockingAssertion library, parametric/table-based tests, package.preload mocking, dependency injection, coverage with debug.sethook, busted.
15Best Practices & PatternsStrict mode, module design, error architecture, RAII via <close>, config layering, logging, anti-patterns catalog.
16Capstone ProjectsJSON parser, coroutine pipeline, ORM query builder, plugin sandbox system, LRU cache, binary search, type checker, mini-REPL.

Learning Path Suggestions

If you're coming from Python/Ruby

Focus on:

  • 02 — _ENV and integer/float duality are unique to Lua
  • 05 — tables are not dicts; array/hash duality
  • 07 — metatables are not __getattr__; __index/__newindex as proxies
  • 11 — coroutines are stackful (can yield from nested calls)

If you're coming from JavaScript

Focus on:

  • 01 — load() with custom env is like new Function() + with
  • 02 — 1-indexed arrays, only nil/false are falsy (0 and "" are truthy)
  • 06 — Lua patterns are NOT regex (no |, no lookahead, % instead of \)
  • 07 — metatables are like Proxy but older and more limited
  • 11 — coroutines are like generators but stackful (no yield* needed)

If you're embedding Lua in C / a game engine

Read all chapters, then focus on:

  • 01 — load() with sandbox env is your security boundary
  • 02 — types map to C types (table → lua_Table, userdata → C object)
  • 05 — tables are the data interchange format with C
  • 07 — metatables for custom C types and operator overloading
  • 08 — package.preload for embedded modules (no filesystem)
  • 15 — strict mode for catching bugs in untrusted scripts

If you're a senior engineer

Skim 01–04. Read deeply:

  • 05 (Tables — the data model)
  • 07 (Metatables — the extension mechanism)
  • 11 (Coroutines — the concurrency primitive)
  • 13 (Performance — where LuaJIT changes the game)
  • 16 (Capstone — integration of all concepts)

Key Differences from Other Languages

ConceptLuaJavaScriptPython
Array indexing1-based0-based0-based
Falsy valuesnil, false only0, "", null, false0, "", None, False
Composite typeTable (only)Object/Array/Mapdict/list/tuple/set
RegexLua patterns (simpler)Full regexre module
Inheritance__index chainPrototype chainClass-based
ConcurrencyCoroutines (cooperative)async/await (event loop)asyncio (event loop)
Ternarya and b or c (trap!)a ? b : cb if a else c
Block scopelocal in blockslet/const in blocksYes (functions/classes)
Tail callsGuaranteed (PTC)No (most engines)No (recursion limit)
String interningYes (all strings)Some (interned literals)Some (interned literals)
Module systemrequire + package.loadedimport/requireimport/__import__

Tooling

ToolPurposeInstall
luaReference interpreter (PUC-Rio)brew install lua
luajitJIT compiler (10-100x faster)brew install luajit
luarocksPackage managerbrew install luarocks
luacheckStatic analyzer (globals, shadowing)luarocks install luacheck
bustedBDD test frameworkluarocks install busted
luaunitLightweight test frameworkluarocks install luaunit
lfsLuaFileSystem (directory access)luarocks install luafilesystem
lpegParsing Expression Grammarsluarocks install lpeg
cjsonFast JSON (C-backed)luarocks install lua-cjson
luasocketNetworking (TCP/UDP/HTTP)luarocks install luasocket