Modules & Libraries

Create and use Lua modules for code organization

Modules in Lua

Learn how to create and use Lua modules to organize your code into reusable components.

Creating a Module

Modules in Lua are typically created using tables that are returned at the end of the file:

mathUtils.lua
-- mathUtils.lua
local mathUtils = {}

function mathUtils.add(a, b)
  return a + b
end

function mathUtils.subtract(a, b)
  return a - b
end

function mathUtils.multiply(a, b)
  return a * b
end

function mathUtils.divide(a, b)
  if b == 0 then
    error("Cannot divide by zero")
  end
  return a / b
end

return mathUtils

Using a Module

You can import modules using the require function:

main.lua
-- main.lua
local mathUtils = require("mathUtils")

local sum = mathUtils.add(5, 3)
print("Sum: " .. sum)

local difference = mathUtils.subtract(10, 4)
print("Difference: " .. difference)

local product = mathUtils.multiply(6, 7)
print("Product: " .. product)

local quotient = mathUtils.divide(20, 5)
print("Quotient: " .. quotient)

Module Search Path

In Lua, the require function searches for modules in the paths specified in package.path. In Roblox, modules are typically placed in ReplicatedStorage and accessed using require(game.ReplicatedStorage.ModuleName).