Writing a Module File
Create a module by returning a table of functions from a .lua file.
The Basic Module Pattern
The standard Lua module pattern: create a local table M, add functions and values to it, and return it at the end. The table is the module's public API. All other locals in the file are private.
-- stringutils.lua
local M = {}
function M.trim(s)
return s:match("^%s*(.-)%s*$")
end
function M.split(s, sep)
local t = {}
for p in s:gmatch("[^"..sep.."]+") do t[#t+1]=p end
return t
end
return M
-- Usage:
-- local su = require("stringutils")
-- print(su.trim(" hello "))Private State
Variables declared local in the module file are private — callers cannot access them. Functions in the module can access private state as upvalues. This is Lua's encapsulation mechanism.
-- counter.lua
local M = {}
local count = 0 -- private state
function M.increment(n)
count = count + (n or 1)
end
function M.reset()
count = 0
end
function M.get()
return count
end
return MAll lessons in this course
- The require Function
- Writing a Module File
- package.path and package.cpath
- Module Patterns and Best Practices