Lesson 48 of 55
9 mins readPython Modules, Packages & the require() System
In Plain English
A module in Lua is simply a table containing functions and constants that is returned at the end of a file: `return M`. Import modules using `local M = require("modname")`.
Deep Dive: How It Works
Module Pattern: Declare `local M = {}`, attach methods, and finish with `return M`.
require(modname): Searches paths in `package.path`, loads the file once, and caches it in `package.loaded`.
Encapsulation: Functions not attached to `M` remain private to the module file.
Core Rules to Remember

return M Convention: Every Lua module returns a table defining its public API.

package.loaded Caching: Subsequent calls to `require()` return the cached module table.
Live Interactive Example
Hit Run Code to see it liveDefining and Using a Module Table
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output Console
Click "Run Code" to view the rendered output.
How it works: MathUtils exposed square and clamp as public module functions.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Define StringUtils Module
Create `local StringUtils = {}`.
Add `function StringUtils.quote(s) return """ .. s .. """ end`.
Print `"Quoted: " .. StringUtils.quote("Lua")`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.