Modules & Packages in Lua
Modules are the basic unit of code organization in Lua. They help you organize your code into reusable components and manage dependencies between different parts of your program.
Creating Modules
A Lua module is typically a table containing functions and variables:
-- File: mymodule.lua
local M = {} -- Create a module table
function M.greet(name)
return "Hello, " .. name
end
function M.add(a, b)
return a + b
end
return M -- Return the module table
Loading Modules
You can load modules using require
:
-- File: main.lua
local mymodule = require("mymodule")
print(mymodule.greet("Alice")) -- "Hello, Alice"
print(mymodule.add(2, 3)) -- 5
Module Search Path
Lua looks for modules in paths specified in package.path
(for Lua) and package.cpath
(for C):
print(package.path)
-- Typical output (may vary by system):
-- ./?.lua;/usr/local/share/lua/5.4/?.lua;/usr/local/share/lua/5.4/?/init.lua
Package Management with LuaRocks
LuaRocks is the package manager for Lua modules:
- Install a package:
luarocks install packagename
- Search for packages:
luarocks search pattern
- Create your own rockspecs to distribute packages
Creating a Package
A package is a collection of modules with a standard structure:
my_package/
├── init.lua
├── module1.lua
└── module2.lua
The init.lua
file is loaded when you require
the package.
Environment Handling
Modules can control their environment to avoid polluting the global namespace:
-- Module with private environment
local M = {}
local _ENV = {print=print, table=table, M=M} -- Whitelist allowed globals
function M.cleanFunction()
-- Can only access whitelisted globals
return table.concat({"Hello", "from", "clean", "module"}, " ")
end
return M
Hot-Reloading Modules
For development, you can implement module reloading:
function reload_module(name)
package.loaded[name] = nil -- Force reload
return require(name)
end
local mymodule = reload_module("mymodule")
Next Steps
Now that you understand modules and packages, learn about coroutines in Lua.