06 - 模块
Lua 模块就是一个返回 table 的脚本文件,通过 require 加载。
一、基本用法
1. 定义模块
-- mymodule.lua
local M = {}
local _private = "hidden" -- 模块内私有
function M.greet(name)
return "Hello, " .. name
end
function M.add(a, b)
return a + b
end
return M -- 导出
2. 加载模块
-- main.lua
local m = require("mymodule")
print(m.greet("Lua")) -- "Hello, Lua"
print(m.add(1, 2)) -- 3
-- 错误处理
local ok, m = pcall(require, "nonexistent")
if not ok then
print("加载失败:", m)
end
二、模块加载机制
1. require 缓存
-- 模块只加载一次,后续 require 返回缓存
package.loaded["mymodule"] -- 缓存表
-- 强制重新加载
package.loaded["mymodule"] = nil
local m = require("mymodule")
2. 搜索路径
print(package.path)
-- "./?.lua;/usr/share/lua/5.4/?.lua;/usr/local/share/lua/5.4/?.lua;..."
-- ? 替换模块名
-- 例如 require("foo.bar") 找 ./foo/bar.lua
3. 自定义搜索路径
package.path = package.path .. ";/my/?.lua;/my/?/init.lua"
local m = require("mymodule") -- 现在也会找 /my/mymodule.lua
三、模块组织模式
1. 经典:返回 table
-- mymodule.lua
local M = {}
M.greet = function(name) ... end
M.add = function(a, b) ... end
return M
2. 简洁:声明全局变量(Lua 5.1 风格)
-- 直接写全局,所有 require 后都能访问
function mymodule_greet(name) ... end
function mymodule_add(a, b) ... end
-- 但污染全局,不推荐
3. 严格模块(Lua 5.2+)
-- 用 _ENV 隔离,完全沙盒
local M = {}
-- 在模块作用域内所有引用自动 local
return M
4. 命名空间
-- 创建嵌套命名空间
local M = {}
M.sub = require("mymodule.sub")
M.utils = require("mymodule.utils")
return M
-- 使用
local app = require("myapp")
print(app.sub.foo())
四、模块元信息
-- 模块可以设置元表,控制访问
local M = {}
setmetatable(M, {
__index = function(_, key)
error("module has no field: " .. key, 2)
end,
__newindex = function(_, key, _)
error("module is read-only", 2)
end,
})
return M
五、面向对象模块
-- shape.lua
local Shape = {}
Shape.__index = Shape
function Shape.new(name)
local s = setmetatable({}, Shape)
s.name = name
return s
end
function Shape:area()
return 0
end
function Shape:describe()
return self.name .. " with area " .. self:area()
end
return Shape
-- main.lua
local Shape = require("shape")
local s = Shape.new("circle")
print(s:describe())
六、LuaRocks 包管理
# 安装 LuaRocks
brew install luarocks
sudo apt install luarocks
# 安装包
luarocks install luasocket
luarocks install lpeg
# 列出已安装
luarocks list
# 查找
luarocks search json
# 卸载
luarocks remove luasocket
-- 使用 LuaRocks 安装的库
local socket = require("socket")
local tcp = socket.tcp()
tcp:connect("example.com", 80)
七、综合实战:多模块项目
1. 项目结构
myapp/
├── main.lua
├── src/
│ ├── app.lua # 主模块
│ ├── config.lua # 配置
│ ├── logger.lua # 日志
│ └── utils.lua # 工具
└── tests/
└── test_logger.lua
2. src/config.lua
local M = {}
M.defaults = {
host = "0.0.0.0",
port = 8080,
debug = false,
}
function M.load(path)
local f = io.open(path, "r")
if not f then return M.defaults end
local content = f:read("*a")
f:close()
-- 简化:解析 KEY=VALUE
local cfg = {}
for k, v in pairs(M.defaults) do cfg[k] = v end
for line in content:gmatch("[^\r\n]+") do
local k, v = line:match("^%s*(%w+)%s*=%s*(%S+)%s*$")
if k and cfg[k] ~= nil then
cfg[k] = v
end
end
return cfg
end
return M
3. src/logger.lua
local M = {}
local LEVELS = {debug = 0, info = 1, warn = 2, error = 3}
function M.new(level)
local self = {level = LEVELS[level or "info"]}
setmetatable(self, {__index = M})
return self
end
function M:log(level, msg)
if LEVELS[level] < self.level then return end
local ts = os.date("%Y-%m-%d %H:%M:%S")
io.write(string.format("[%s] [%s] %s\n", ts, level:upper(), msg))
io.flush()
end
function M:debug(msg) self:log("debug", msg) end
function M:info(msg) self:log("info", msg) end
function M:warn(msg) self:log("warn", msg) end
function M:error(msg) self:log("error", msg) end
return M
4. src/utils.lua
local M = {}
function M.split(s, sep)
sep = sep or ","
local parts = {}
local pattern = "([^" .. sep .. "]+)"
for part in s:gmatch(pattern) do
table.insert(parts, part)
end
return parts
end
function M.trim(s)
return s:match("^%s*(.-)%s*$") or s
end
function M.starts_with(s, prefix)
return s:sub(1, #prefix) == prefix
end
function M.ends_with(s, suffix)
return s:sub(-#suffix) == suffix
end
return M
5. src/app.lua
local config = require("config")
local Logger = require("logger")
local utils = require("utils")
local M = {}
function M.run(args)
local cfg = config.load(args[1] or "config.ini")
local log = Logger.new(cfg.debug and "debug" or "info")
log:info("启动: " .. cfg.host .. ":" .. cfg.port)
local parts = utils.split("a,b,c", ",")
log:debug("split 结果: " .. #parts)
return cfg
end
return M
6. main.lua
-- 修改 package.path 加载本地模块
package.path = "./src/?.lua;" .. package.path
local app = require("app")
app.run(arg)
7. 运行
lua main.lua
# [2024-01-15 10:30:00] [INFO] 启动: 0.0.0.0:8080
# [2024-01-15 10:30:00] [DEBUG] split 结果: 3
八、要点速记
- 模块 = 返回 table 的脚本
require(modname)加载,带缓存- 搜索路径:
package.path,?替换模块名 - 私有变量用
local,不会污染全局 - 修改
package.path扩展搜索路径 package.loaded[modname] = nil强制重载pcall(require, ...)安全加载- LuaRocks 是标准包管理工具
- 面向对象模块用
setmetatable + __index