TExcelTAD
Home › Lua › Lua Modules

Lua Modules

A module is a piece of code you can load and reuse from other files. In Lua a module is simply a file that builds a table of functions and values and returns it. The require function loads that file once and hands the table to whoever asks for it.

The module table pattern

A module file, say geometry.lua, typically looks like this:

lua
-- geometry.lua
local M = {}                      -- the module table

local function square(x)          -- private: not in M
  return x * x
end

function M.circleArea(r)
  return math.pi * square(r)
end

function M.distance(x1, y1, x2, y2)
  return math.sqrt(square(x2 - x1) + square(y2 - y1))
end

M.VERSION = "1.0"

return M                          -- what require() gives back

And the code that uses it:

lua
-- main.lua
local geometry = require("geometry")   -- finds geometry.lua via package.path
print(geometry.distance(0, 0, 3, 4))   --> 5.0

Everything declared local in the file is private to the module; only what you put in M is visible from outside. There are no special keywords: it's plain tables and locals.

Trying require in one file

The playground runs a single file, but we can still use the real require. package.preload is a table of loader functions: require(name) checks it before searching the disk. Registering a loader there simulates a separate file:

lua · try it yourself
package.preload["geometry"] = function()
  local M = {}
  local function square(x) return x * x end
  function M.circleArea(r) return math.pi * square(r) end
  function M.distance(x1, y1, x2, y2)
    return math.sqrt(square(x2 - x1) + square(y2 - y1))
  end
  M.VERSION = "1.0"
  return M
end

local geometry = require("geometry")
print(geometry.VERSION)
print(geometry.distance(0, 0, 3, 4))
print(string.format("%.2f", geometry.circleArea(1.5)))
print(geometry.square)          -- private helper: not exported
1.0
5.0
7.07
nil

require loads only once

require caches each module in package.loaded. Later calls return the same table without running the file again, so every part of a program shares one copy of the module's state:

lua · try it yourself
local loads = 0
package.preload["counter"] = function()
  loads = loads + 1
  local M = { value = 0 }
  function M.bump() M.value = M.value + 1; return M.value end
  return M
end

local a = require("counter")
local b = require("counter")
a.bump(); b.bump()
print(a == b, a.value, "loads: " .. loads)
print(package.loaded["counter"] == a)
print(package.loaded["string"] == string)
true	2	loads: 1
true
true

Even the standard libraries are registered in package.loaded. To force a reload during development, set package.loaded["counter"] = nil and call require again.

How require finds files

Step What require("a.b") does
1 returns package.loaded["a.b"] if it is already loaded
2 calls package.preload["a.b"] if present
3 searches package.path for a Lua file, replacing ? with a/b
4 searches package.cpath for a C library (.so/.dll)
5 raises "module 'a.b' not found" with the list of places it tried

A typical package.path is ./?.lua;./?/init.lua;/usr/local/share/lua/5.4/?.lua;…, so require("utils.strings") finds ./utils/strings.lua, and a folder module require("ui") finds ./ui/init.lua.

lua · try it yourself
local ok, err = pcall(require, "no_such_module")
print(ok)
print(err:match("^[^\n]+"))
false
module 'no_such_module' not found:

Module design tips

  • Return a table, don't create globals. Old Lua 5.0 code used module(...), which created global tables; it was removed in 5.2.
  • Name the local the same as the module: local json = require("json").
  • Keep state explicit. Module-level variables are shared by all users; for per-user state, have the module return a constructor (a class) instead.
  • Use ... for the module name. Inside a module file, ... holds the name it was required with, which helps when requiring sibling modules: local helpers = require((...):match("(.-)[^.]+
    quot;) .. "helpers")
    .

Classes as modules

Very often a module is a class:

lua · try it yourself
package.preload["Stack"] = function()
  local Stack = {}
  Stack.__index = Stack
  function Stack.new() return setmetatable({ items = {}, size = 0 }, Stack) end
  function Stack:push(v) self.size = self.size + 1; self.items[self.size] = v end
  function Stack:pop()
    if self.size == 0 then return nil end
    local v = self.items[self.size]
    self.items[self.size] = nil
    self.size = self.size - 1
    return v
  end
  return Stack
end

local Stack = require("Stack")
local s = Stack.new()
s:push("a"); s:push("b"); s:push("c")
print(s:pop(), s:pop(), s.size)
c	b	1

Test yourself

What does a typical Lua module file return?

  1. Nothing; it sets globals
  2. A table of its public functions and values
  3. A string with its name
  4. true

What happens when you require the same module twice?

  1. The file runs twice
  2. The second call returns the cached table from package.loaded
  3. An error is raised
  4. A copy of the table is returned

Where does require("net.http") look for a Lua file?

  1. In package.path, with ? replaced by net/http
  2. Only in the current folder as net.http
  3. In _G.net
  4. On LuaRocks.org