Lua by Example: Modules
Modules allow you to organize code into reusable files. This sample shows how to create and require a simple module.
Code
-- mymodule.lua
local M = {}
-- Private variable
local secret = 42
-- Public function
function M.greet(name)
return "Hello, " .. name
end
function M.getSecret()
return secret
end
return M
-- main.lua
-- local mymod = require("mymodule")
-- print(mymod.greet("Lua"))Explanation
Lua modules are simply files that return a table containing functions and variables. The standard way to create a module is to define a local table (often named M), attach functions to it, and then return that table at the end of the file. This encapsulates the code and avoids polluting the global namespace.
To use a module, you use the require function. require("filename") searches for the file in the paths defined by package.path, executes it, and returns the value returned by the file (usually the module table). Lua caches loaded modules in package.loaded, so subsequent calls to require return the cached table without re-executing the file.
Variables declared local inside the module file remain private to that module. They are accessible by the module's functions via closures (upvalues) but are invisible to the outside world. This provides a clean way to implement private state and helper functions.
Code Breakdown
local M = {} creates the table that will hold the public interface of the module.return M exports the table. The return value of the chunk becomes the result of require.
