0Pricing
Lua Academy · Lesson

The require Function

Load external modules with require and understand module caching.

How require Works

require(modname) loads and returns a module. It searches package.path for a .lua file and package.cpath for a C library. The result is cached in package.loaded[modname] — subsequent calls return the cached value without re-executing the file.

-- First require: loads and executes math_utils.lua
local math_utils = require("math_utils")

-- Second require: returns cached value (file not re-run)
local math_utils2 = require("math_utils")

print(math_utils == math_utils2)   -- true (same object)
print(package.loaded["math_utils"] == math_utils)  -- true

Module Return Value

A module file should return a value — typically a table of functions. This return value is what require gives back to the caller. If the file returns nothing (or true), that's what require returns.

-- mymodule.lua:
-- local M = {}
-- function M.hello() print("Hello from module!") end
-- return M

-- In main script:
local m = require("mymodule")
m.hello()   -- Hello from module!

-- The module table is the interface

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