Skip to content
Lua

Modules

Create reusable modules in Lua.

By EZ4Code Team
modulerequire

Code

-- File: mathutils.lua
local M = {}  -- module table

function M.square(x) return x * x end
function M.cube(x) return x * x * x end

-- Private (not in M)
local function helper(x) return x + 1 end

function M.complex(x)
  return M.square(x) + helper(x)
end

-- Metatable-style module (with __call)
setmetatable(M, {
  __call = function(self, x)
    return x * 2
  end
})

return M

-- Usage in another file:
-- local mathutils = require("mathutils")
-- print(mathutils.square(5))   -- 25
-- print(mathutils.complex(3))  -- 12
-- print(mathutils(10))         -- 20 (via __call)

Explanation

Modules are tables returned from a file. require('name') loads and caches the module. locals are private; assigned fields (M.func) are public. The __call metamethod lets you call the module itself like a function. Package paths are configured via package.path. This pattern is the foundation of Lua's minimal but flexible module system.

More Lua Snippets