Lua with NeoVim: Modules and Require — local M = {}, return M & require() | Episode 24
Video: Lua with NeoVim: Modules and Require — local M = {}, return M & require() | Episode 24 by Taught by Celeste AI - AI Coding Coach
Watch full page →Lua with NeoVim: Modules and Require — local M = {}, return M & require()
In Lua, organizing code into reusable modules is essential for building real-world programs. This tutorial demonstrates the standard Lua module pattern by creating a table M, attaching functions to it, returning M to export the module, and then loading it in another script using require(). We build a simple math tools module and use it side-by-side in NeoVim splits to illustrate modular programming and code reuse.
Code
-- mathtools.lua: Define a module with math functions
local M = {} -- module table
function M.add(a, b)
return a + b
end
function M.subtract(a, b)
return a - b
end
function M.multiply(a, b)
return a * b
end
function M.square(x)
return x * x
end
function M.is_even(n)
return n % 2 == 0
end
return M -- export the module
-- main.lua: Load and use the mathtools module
local mt = require("mathtools") -- load the module
print("Add 2 + 3 = " .. mt.add(2, 3))
print("Subtract 5 - 1 = " .. mt.subtract(5, 1))
print("Multiply 4 * 6 = " .. mt.multiply(4, 6))
print("Square of 7 = " .. mt.square(7))
local n = 10
print("Is " .. n .. " even? " .. tostring(mt.is_even(n))) -- tostring converts boolean to string for concatenation
Key Points
- The module pattern uses a local table
Mto hold functions and data to be exported. - Functions are attached as fields on
M(e.g.,M.add) to expose them outside the module. - Returning
Mat the end of the file exports the module for use withrequire(). require("module")loads, runs, and caches the module, returning the exported table.- Use
tostring()to convert boolean results to strings when concatenating for output.