Lua Coding Guidelines
Requirements
- Lua ≥ 5.4.
Essentials
- Module pattern - Always
local, one module per file returning table, see references/module-pattern.md, references/local-variables.md - Code organization - Prefer table-based modules and simple functions, see references/module-pattern.md, references/metatables.md
- Cooperative tasks - Use coroutines for async patterns, see references/coroutines.md
- Validation - Validate inputs, see references/input-validation.md
- Paradigm - Functional style → fp-guide; class/OO design (metatable-based) → oop-guide
Gotchas
- Arrays are 1-indexed; a
nilhole breaks the#length operator (it stops at the first nil) - Tables are both array and hash; mixing them is fine but iteration order isn't guaranteed for the hash part
/always returns a float; use//for integer floor division:total // per_page, notmath.floor(total / per_page)- Variables are global by default unless declared
local: forgettinglocalin a loop counter leaks into the surrounding scope
Progressive disclosure
- Read references/module-pattern.md - Load when creating reusable modules or organizing code structure
- Read references/local-variables.md - Load when encountering global variable issues or scoping problems
- Read references/metatables.md - Load when implementing object-oriented patterns or operator overloading
- Read references/coroutines.md - Load when implementing cooperative multitasking or async patterns
- Read references/input-validation.md - Load when adding type checks or parameter validation
- Read references/idiomatic-patterns.md - Load when learning common Lua idioms or patterns