Sharing Lua with require
As a patch set grows, you end up wanting shared code: a helper that several patch files use, a table of constants, a small library. Lua's require lets you pull one file into another, and PatchManager extends it so you can pull in a library from another mod too.
Library files use the underscore prefix
Recall from file layout and discovery that a .lua file whose name starts with an underscore is not run as a patch. That is exactly what makes it a library: it does not execute on its own, it waits to be required.
So a shared file is named with a leading underscore:
MyMod/
swinfo.json
patches/
engines.lua
tanks.lua
_shared.lua_shared.lua will not run as a patch. engines.lua and tanks.lua pull it in.
Requiring within your mod
To use a library, require it by name without the underscore. PatchManager finds the matching _name.lua in your mod:
-- in _shared.lua
local M = {}
function M.RGB(r, g, b)
return function(body) body.MineDustColor = { x = r, y = g, z = b, w = 1.0 } end
end
return M-- in a patch file
local shared = require("shared") -- loads _shared.lua
PM.Planets:Patch("MohoDustColor"):Named("Moho"):Do(shared.RGB(0.53, 0.39, 0.29))A library returns a value (usually a table of functions), and require hands you that value. The result is cached, so requiring the same library twice gives you the same value rather than running it again. If a library returns nothing, require gives you true, which is enough to confirm it loaded.
Requiring from another mod
PatchManager extends require with a cross-mod form. Prefix the library name with the other mod's id and a colon:
local lib = require("OtherMod:helpers") -- loads _helpers.lua from OtherModThis loads _helpers.lua from the mod whose id is OtherMod. It is how a shared library mod can publish helpers that other patch mods build on. If you depend on another mod's library this way, declare that dependency so your mod does not load without it. See Cross-mod compatibility and the dependencies field in shipping patches.
When to split into libraries
A helper used by more than one patch file: pull it into a
_name.lualibrary.A table of shared constants or data: same.
Code only one file uses: keep it local to that file. A local function at the top of the file is simpler than a library when nothing else needs it.
The goal is the same as in any codebase: share what is shared, keep local what is local.