0Pricing
Lua Academy · Lesson

package.path and package.cpath

Configure search paths for Lua and C modules.

package.path Contents

package.path is a string of search patterns separated by semicolons. Each pattern has a ? placeholder that gets replaced by the module name (with dots converted to directory separators). Lua tries each pattern in order until a file is found.

print(package.path)
-- ./?.lua;./?.luac;/usr/local/share/lua/5.4/?.lua;...

-- Dots in module names become directory separators
-- require("foo.bar") -> searches for foo/bar.lua
print(("foo.bar"):gsub("%.", "/"))  -- foo/bar

Adding Search Paths

Prepend paths to package.path to add search directories. Appending adds lower-priority locations. Set this before any require calls that need the new paths.

-- Add multiple directories
package.path = table.concat({
  "./?.lua",
  "./lib/?.lua",
  "./lib/?/init.lua",
  package.path,  -- keep existing paths
}, ";")

-- Now require("json") searches:
-- ./json.lua -> ./lib/json.lua -> ./lib/json/init.lua -> ...

All lessons in this course

  1. The require Function
  2. Writing a Module File
  3. package.path and package.cpath
  4. Module Patterns and Best Practices
← Back to Lua Academy