luaguides

require

require(modname)

require(modname) is the standard way to load a module in Lua. It looks up modname in the cache, walks a list of searcher functions when the name is not cached, runs the resulting loader, and stores the result in package.loaded so subsequent calls are cheap. The same call returns a value of any Lua type (a table, a function, even true), depending on what the loaded module returns.

Parameters

  • modname (string, required): the module name. Dots are treated as directory separators when resolving the name against package.path or package.cpath. Hyphens have a special meaning for C-module lookup: everything from the first - onward is stripped from the symbol name.

Return Values

require can return one or two values.

  • First value: whatever is stored in package.loaded[modname] when loading finishes. Conventionally a table of functions, but it can be any Lua type. If the module file returns nothing, the cached value is true.
  • Second value: the loader data the searcher returned alongside the loader. For the default file-system searchers this is the file path; for the preload searcher it is the string ":preload:". If the module was already in the cache and require did not have to load it, this second value is not produced. Use select("#", ...) to detect that case.

require raises an error when no searcher can find a loader or when the loader itself fails. Wrap calls in pcall or xpcall to recover from a missing or broken module.

How the searcher chain resolves a module name

Resolution follows the order in package.searchers (a list of functions, not a module). The default list has four entries:

  1. Preload searcher: checks package.preload[modname]. If present, that function becomes the loader and the loader data is ":preload:".
  2. Lua library searcher: substitutes modname into each template in package.path (dots become the directory separator, the ? marker is the substitution point) and tries to open the resulting files in order.
  3. C library searcher: same against package.cpath, then loads the matching dynamic library and looks up a C function named luaopen_ + the module name with . rewritten as _, with everything from the first - onward stripped.
  4. All-in-one loader: for dotted names like a.b.c, asks the C library for the root a to provide luaopen_a_b_c.

When a searcher returns a string, it is treated as a “this is why I failed” message; the next searcher runs. When a searcher returns nil with no message, require silently moves on. When every searcher returns without a loader, require raises an error.

You can inspect the searcher list at runtime to confirm the order and the functions installed by the host. Lua functions print as file:line; C functions print as function: 0x...:

for i, searcher in ipairs(package.searchers) do
    print(i, searcher)
end

A handful of standard configurations reorder these. LuaJIT, for example, replaces the C library searcher with a require-style FFI searcher; some embedded hosts prepend a custom searcher for compressed or encrypted modules.

Worked example: loading a Lua file

Project layout:

project/
├── main.lua
└── lib/
    └── greet.lua

The first file is the module we want to load. Inside lib/greet.lua, we define a single function on a module table and return that table at the end of the file so require can hand it back to the caller:

local M = {}

function M.hello(name)
    return "Hello, " .. tostring(name) .. "!"
end

return M

The entry-point script, main.lua, calls require on the dotted module name, prints the greeting, then prints the file path the loader returned as the second result. The second value is whatever the searcher matched against package.path, so it changes when the search path does:

local greet, path = require("lib.greet")
print(greet.hello("Lua"))
print(path)

To run the example, change into the project directory you just created and invoke the Lua interpreter. Pass the entry-point script as the argument. The interpreter will load greet.lua, cache the result, and execute the two print calls in order:

cd project
lua main.lua

The first value is the module table, the second is the path the searcher matched to load it. On a stock Lua 5.4 build with the default ./?.lua template, the interpreter prints the greeting, the relative path, and nothing else. The actual output looks like this:

Hello, Lua!
./lib/greet.lua

A later require("lib.greet") call returns only the table; the cache hit suppresses the loader-data result, and select("#", require("lib.greet")) reports 1 on that call instead of 2.

Worked example: handling load errors

The simplest way to recover from a missing or broken module is to wrap the call in pcall. If require raises, pcall returns false and the error message in its second value, so the rest of your program can keep running:

local ok, mod = pcall(require, "does_not_exist")
if not ok then
    print("failed to load:" .. mod)
end

With a stock Lua 5.4 installation on Linux and the default search path, the call fails because no candidate file exists on disk. The error message, including the leading space that package.searchpath always emits when it lists the candidates it tried, looks like this:

failed to load:   cannot open does_not_exist: No such file or directory

The error string starts with a leading space because package.searchpath formats its message that way. Strip the leading space if you log or display it, otherwise your output ends up with stray whitespace between fields.

Worked example: shipping a module through package.preload

Hosts that need to ship modules without putting files on disk — frozen bytecode blobs, embedded source strings, modules built at runtime — register a loader function in package.preload under the desired name. The first argument to require then resolves to that loader, exactly the same as a path-based file:

package.preload["embed.utils"] = function()
    local M = {}

    function M.now()
        return os.time()
    end

    return M
end

local utils = require("embed.utils")
print(utils.now())

The loader runs the first time require("embed.utils") is called and the table it returns is cached in package.loaded. Subsequent calls return the same table without re-running the function. The second value require returns on the first call is the loader data string ":preload:"; once the module is cached, select("#", require("embed.utils")) reports 1 instead of 2. Calling package.preload["embed.utils"] = nil removes the registration; the next require then falls through to the path-based searchers and fails unless a real file exists.

The package Library

require reads and writes a small set of tables, all members of the standard package library:

  • package.loaded: the module cache. Set package.loaded[modname] = nil to force a reload. The real table lives in the C registry, so reassigning the local variable package.loaded does not redirect the cache.
  • package.preload: map of modname -> loader function. Use it to ship modules inside a single file, a frozen bytecode blob, or an embedded host.
  • package.path: search path for Lua modules, with ? as the substitution marker and ; between templates. Initialized from LUA_PATH_5_4 or LUA_PATH at startup.
  • package.cpath: same shape as package.path, for C modules. Initialized from LUA_CPATH_5_4 or LUA_CPATH.
  • package.config: five-line compile-time configuration: directory separator, path-template separator, substitution marker, Windows executable-dir marker, and C-name suffix-strip marker.
  • package.searchers: the list of searcher functions. Default length is 4. Reorder, replace, or remove entries to change how require resolves names.
  • package.searchpath(name, path [, sep [, rep]]): helper that walks a path template, replaces ? with name (mapping sep to rep, defaulting to . and the directory separator), and returns the first readable file or nil plus an error message.

A few direct uses of those tables and functions come up often enough to be worth seeing as code. package.searchpath runs the same path-template search require uses internally, so it is the right tool when you want to find a module file without loading it. Mutating package.loaded[modname] is the standard way to force a reload, because require always checks the cache before walking the searcher list. Adding a directory to package.path is a one-line concatenation, and is how most projects make sibling modules discoverable:

-- Find the file Lua would load for a given module name
local file, err = package.searchpath("foo", package.path)
if not file then
    print("not found:", err)
end

-- Force a module to be reloaded on the next require
package.loaded["foo"] = nil

-- Make a project's own directory searchable
package.path = "./src/?.lua;./src/?/init.lua;" .. package.path

Common Mistakes with require

  • Returning nil from a module. A module that does return (or return nil) makes require cache true for that name. The next call returns the cached true, and m.doThing() will error with attempt to index a boolean. Always return a table (or a function) from a module file.
  • Forgetting to mutate package.loaded in place. Reassigning the local variable package.loaded does not affect the cache, because the real table is in the C registry. Use package.loaded[modname] = nil to force a reload, not package.loaded = {}.
  • Hyphens in C-module names. require("luasocket-2.1") looks up the symbol luaopen_luasocket, with the -2.1 suffix stripped. If your C source defines luaopen_luasocket_2_1, the lookup will fail at link time. Strip the version suffix in the require call, or match the C symbol. As a quick reference, the symbol mapping for a few common names is:
    -- require("foo")        -> luaopen_foo
    -- require("foo.bar")    -> luaopen_foo_bar
    -- require("foo-1.2")    -> luaopen_foo
    -- require("a-b-c")      -> luaopen_a
  • Relative paths depend on the current working directory. The default ./?.lua template resolves against the directory Lua was launched from, not the script’s location. Prepend the script’s directory to package.path at startup if you need to find sibling modules.
  • Setting package.loaded[modname] = false. This is a documented sentinel: it tells require to skip the cache and try to load anyway. Useful in tooling, easy to misuse in regular code.

The first two mistakes show up in real code as small but loud errors. The return-with-no-value module fails the moment a caller indexes the result, and the reassignment trap silently leaves the old cache intact. A single annotated block is enough to show both, because the bad and good versions are almost the same shape:

-- bad_module.lua — caches `true` in package.loaded
-- any caller that does `m.do_thing()` then errors with
-- `attempt to index a boolean (local 'm')`
return

-- good_module.lua — returns a table the caller can use
local M = {}
function M.do_thing() end
return M

The reassignment trap looks similar in shape. The first call below looks like it empties the cache, but require keeps reading the real table out of the C registry, so subsequent loads still hit the cached entries. Mutating the same table in place with package.loaded[modname] = nil is the only way to force a fresh load:

-- Does NOT clear the cache (reassigns the local)
package.loaded = {}

-- Does clear the cache entry (mutates the real table)
package.loaded["foo"] = nil

If you need to reload a module repeatedly (test harnesses, REPL-style tools, hot-reload servers), the right pattern is a small helper rather than open-coding package.loaded access everywhere:

local function reload(name)
    package.loaded[name] = nil
    return require(name)
end

See also

  • Modules and require: step-by-step tutorial covering the same behavior with longer examples.
  • Error handling basics: pcall and xpcall for recovering from load errors.
  • pcall: companion reference for catching errors thrown by require.