Skip to content
Modules and require
step 1/5

Reading — step 1 of 5

Learn

~1 min readModules, Iterators, I/O

A module is just a Lua file that returns a table. require("name") loads it once and caches the result.

Module patternmathx.lua:

local M = {}

function M.square(n) return n * n end
function M.cube(n)   return n ^ 3 end

local SECRET = 42      -- not exported (local to file)

return M

Consumer:

local mathx = require("mathx")
print(mathx.square(7))   -- 49
print(mathx.cube(3))     -- 27

require searches package.path (a ;-separated list of patterns where ? is replaced by the module name). Default includes ./?.lua and ./?/init.lua.

Caching: subsequent require("mathx") calls return the same table — your module's top-level code runs only once. To force a reload (development), package.loaded["mathx"] = nil then require again.

Submodule pattern:

  • File myapp/strings.lua is required as require("myapp.strings") (dot becomes slash).
  • File myapp/init.lua becomes the require("myapp") entry point.

package.path and package.cpath:

  • package.path — Lua source modules
  • package.cpath — C extensions (.so / .dll)

You can prepend custom paths:

package.path = "./libs/?.lua;" .. package.path

No globals: a well-behaved module never assigns to a global — only to its returned table.

LuaRocks is the package manager — handles versioned dependencies, native compilation. Most ecosystem libraries (LPeg, LuaSocket, OpenResty stack) install via LuaRocks.

In this sandbox you can demonstrate the pattern by defining a 'module' as a local table within one file (not split across files).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…