Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 37 ยท Luau Scripting

Modules, Types and Strict Mode

Organise Roblox code with ModuleScripts and require, then catch bugs early with Luau type annotations, custom types, optionals, unions and --!strict mode.

As a game grows, one giant script becomes impossible to read. Roblox solves this with ModuleScripts, files that hold reusable code. Luau adds a second tool for big projects: optional types that let Studio find mistakes before you press Play. This lesson covers both.

ModuleScripts

A ModuleScript is a script that does not run on its own. It returns one value, usually a table of functions, and other scripts load it with require.

Create a ModuleScript in ReplicatedStorage, name it MathUtil, and write:

LUA
-- ReplicatedStorage/MathUtil (a ModuleScript)
local MathUtil = {}

function MathUtil.average(numbers: {number}): number
	local total = 0
	for _, n in numbers do
		total += n
	end
	return total / #numbers
end

function MathUtil.roundTo(value: number, places: number): number
	local factor = 10 ^ places
	return math.round(value * factor) / factor
end

return MathUtil

Then use it from a Script:

LUA
-- ServerScriptService/Script
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local MathUtil = require(ReplicatedStorage:WaitForChild("MathUtil"))

print(MathUtil.average({4, 8, 12}))     --> 8
print(MathUtil.roundTo(3.14159, 2))     --> 3.14

Key rules:

  • A ModuleScript must return exactly one value (a table, function or other value).
  • require runs the module the first time and caches the result. Every later require in the same environment gets the same table. This makes a module a natural place for shared state, such as one table holding all game settings.
  • The server and each client have separate copies. A module in ReplicatedStorage can be required on both sides, but each side gets its own table; changes are not shared across the network.
  • Put server-only modules in ServerScriptService or ServerStorage so clients can never read them. See the services lesson.

You can also require a module by relative path, such as require(script.Parent.MathUtil), which keeps related code together.

A module that holds state

LUA
-- Module: Inventory
local Inventory = {}
local items = {}

function Inventory.add(name: string, count: number)
	items[name] = (items[name] or 0) + count
end

function Inventory.count(name: string): number
	return items[name] or 0
end

return Inventory

The private items table lives in the module; only add and count can touch it. This hiding of details is called encapsulation, and later chapters use it for player data.

Why types?

Luau checks types only when you ask it to, and it never slows your game. Annotations help you in three ways: Studio autocompletes better, wrong calls get a yellow or red underline immediately, and the code documents itself.

Annotating variables and functions

Put a colon and a type after a name:

LUA
local score: number = 0
local playerName: string = "Mira"
local isAlive: boolean = true

local function damage(health: number, amount: number): number
	return health - amount
end

damage(100, "ten")    -- Studio underlines "ten": expected number, got string

Common types: number, string, boolean, nil, any (turns checking off), Instance, Part, Vector3, Color3, (array of numbers), {[string]: number} (dictionary), and function types like (number, number) -> number.

Optional values, unions and literals

A trailing ? makes a type optional, so it may be nil:

LUA
local target: Part? = workspace:FindFirstChild("Target") :: Part?

if target then
	print(target.Position)    -- inside the if, Luau knows it is a Part
end

A union allows several types, and a string literal restricts the options:

LUA
type Id = number | string
type Direction = "left" | "right" | "up" | "down"

local function move(direction: Direction)
	print("moving", direction)
end

move("left")
move("sideways")     -- flagged: not a valid Direction

The :: operator is a type cast that tells Luau "trust me, this is a Part." Use it sparingly; a wrong cast hides a bug.

Custom types

Use type to name a shape, typically a table:

LUA
type Item = {
	name: string,
	price: number,
	tags: {string}?,       -- optional list of strings
}

local sword: Item = {name = "Sword", price = 50}
local shield: Item = {name = "Shield", price = "cheap"}   -- flagged: price should be number

Export a type from a module so other scripts can use it:

LUA
export type Item = {name: string, price: number}

Strict mode

Add a directive on the very first line of a script to change how thorough the checker is:

Directive Behaviour
--!nocheck No type checking
--!nonstrict The default; unknown types are treated as any
--!strict Every variable and parameter must have a known type
LUA
--!strict
local function double(n: number): number
	return n * 2
end

In strict mode a function parameter without a type is an error, so you are guided into typing the whole script. Many professional Roblox projects use --!strict in all modules. You can start with --!nonstrict and add types gradually, which is why Luau types are called gradual.

Stand-in: a module and require cache

Real require is provided by Roblox. This JavaScript stand-in models its two key behaviours: the module body runs once, and later requires return the same cached value.

JS Stand-in: require runs a module once (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Stand-in: a tiny type checker

Studio's checker is far more capable, but the idea is simple: compare a value against a described shape. This toy checks tables against a type like Item.

JS Stand-in: checking a table against a type (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The real checker reports these before the game even starts, as underlines in the editor.

Practical advice

  • Start every new ModuleScript with --!strict and a typed public API.
  • Return a table of functions; keep helper functions local and unexposed.
  • Avoid circular requires (A requires B and B requires A); it hangs. Move shared code to a third module.
  • Use any only when you must; it switches off checking for that value.
  • Keep one module per concern: Inventory, DataService, Config.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must a ModuleScript do?

    A ModuleScript returns one value, usually a table, which require hands to the caller.
  2. 2. How many times does a module body run when several scripts require it?

    The first require runs the module; later requires return the cached value.
  3. 3. What does the type Part? mean?

    A trailing ? makes the type optional, so the value may be nil.
  4. 4. Which directive makes Luau require types on all variables and parameters?

    --!strict turns on the strictest checking.

Summary

  • ModuleScripts return one value; require runs them once and caches the result.
  • Keep private state in local variables inside a module and expose only functions.
  • Annotate with name: type; use ? for optional, | for unions and type for custom shapes.
  • --!strict turns on full checking, and types never slow the game.

Next: Creating and Configuring Parts in Code