In Lua, a Module is simply a script file that returns a table containing functions, constants, and types. Lua uses the built-in require() function to load and cache modules.
Authoring a Clean Encapsulated Module
-- File: network/http_client.lua
local HttpClient = {}
HttpClient._VERSION = "1.2.0"
-- Private constants and functions (invisible to outside callers)
local DEFAULT_TIMEOUT = 30
local function sanitizeHeaders(headers)
return headers or { ["User-Agent"] = "CodeAcademixLua/1.0" }
end
-- Public API
function HttpClient.get(url, headers)
local activeHeaders = sanitizeHeaders(headers)
print(string.format("Dispatching GET %s with timeout %ds", url, DEFAULT_TIMEOUT))
return { status = 200, body = "OK" }
end
function HttpClient.post(url, payload, headers)
local activeHeaders = sanitizeHeaders(headers)
print("Dispatching POST " .. url)
return { status = 201, body = "Created" }
end
-- MUST return the module table!
return HttpClient
Consuming Modules with require()
-- File: main.lua
local http = require("network.http_client")
local response = http.get("https://api.codeacademix.dev/health")
print("Response Status: " .. response.status)
How require() Works Under the Hood
When you call require(modname):
- Cache Inspection: Lua checks the global table
package.loaded[modname]. If the module was already required, it returns the cached table immediately without re-evaluating the file. - Search Path Scanning: If not cached, Lua searches the filesystem templates in
package.path(for Lua scripts) andpackage.cpath(for compiled C dynamic libraries.so/.dll). - Execution & Caching: The file is executed as a chunk, its return value is stored into
package.loaded[modname], and returned to the caller.
-- Inspecting and customizing the search path
print("Current Lua search path: " .. package.path)
-- Force module reloading (useful in hot-reload game engines)
package.loaded["network.http_client"] = nil
local freshModule = require("network.http_client")
Exercises
- Build a logger module supporting configurable log levels (
DEBUG,INFO,ERROR) and file output. - Implement a runtime hot-reloader that re-requires modified Lua files during an active game loop.
- Explain how
package.preloadcan embed modules directly in memory without disk access.