Skip to content
Lua

Modules

Créer des modules réutilisables en Lua.

#module#require

Code

lua
-- 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)