0Pricing
Lua Academy · Lesson

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 M

All lessons in this course

  1. The require Function
  2. Writing a Module File
  3. package.path and package.cpath
  4. Module Patterns and Best Practices
← Back to Lua Academy