LU

Lua Module and OOP Architecture

Structuring Lua applications with the module pattern, metatables, and prototype-based OOP

Details

Language / Topic
luaLua
Category
Architecture

Rules

balanced
- Use the module-as-table pattern: define `local M = {}` at the top, populate `M.funcname = function()`, and `return M` at the end.
- Implement classes with a constructor that sets `self.__index = self` and a `new` function that uses `setmetatable({}, Class)`.
- Separate module public API from private helpers by keeping private functions as `local function helper()` not assigned to `M`.
- Use `__index` metamethod for prototype-chain inheritance: `setmetatable(Child, { __index = Parent })` delegates unknown method lookups to `Parent`.
- Use `__tostring`, `__eq`, `__lt`, and `__add` metamethods on class metatables to give instances idiomatic operator behavior.
- Organize large projects as a directory of modules: `require('myapp.router')`, `require('myapp.db')` — configure `LUA_PATH` to include the project root.
- Use `package.loaded['modname'] = mod` in tests to inject mock modules before the code under test calls `require('modname')`.