Nanfeng

Notes on software development, code, and curious ideas

Import Versus Require in Lua

Standard Lua provides require; it does not define a global import function. If a project supports import, that function comes from a framework such as a game engine or from the application’s own utility code, so its exact behavior must be checked in that project.

Loading with require

Given tools/mathx.lua:

1
2
3
4
5
6
7
local M = {}

function M.double(value)
return value * 2
end

return M

Load it with a dotted module name:

1
2
local mathx = require("tools.mathx")
print(mathx.double(21))

require checks package.loaded, uses the configured searchers and paths to find a Lua or C module, executes the loader once, caches its result, and returns that result on later calls. If a loader returns nil, Lua normally records true to mark it loaded.

What import often does

Framework implementations frequently wrap require while adding a relative module name, a custom root, automatic reloading, or engine-specific lookup. For example, a project could define:

1
2
3
4
local function import(name, packageName)
local prefix = packageName and (packageName .. ".") or ""
return require(prefix .. name)
end

That is only an example—not portable Lua behavior. Two frameworks can expose functions named import with incompatible rules.

Use require for reusable Lua modules unless the host framework explicitly expects its loader. Avoid relying on current working directories; configure package.path deliberately or use module names that match the deployed directory structure. Modules should return a table or function rather than install globals.

+