Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 37 ยท Luau Scripting

Functions, Events and Errors in Luau

Write Luau functions with parameters and returns, use closures and varargs, connect to Roblox events, handle errors with pcall, and run code later with task.spawn and task.delay.

A function is a named, reusable piece of code. Roblox is built on them: every event handler, every button click and every game rule is a function. This lesson shows how to write functions, pass them around, connect them to Roblox events, and protect your game from errors with pcall.

Defining and calling functions

LUA
local function greet(name)
	print("Hello, " .. name .. "!")
end

greet("Mira")     --> Hello, Mira!
greet("Theo")     --> Hello, Theo!

local function creates a local function. Parameters (name) are variables that receive the values passed in. Use return to send a value back:

LUA
local function add(a, b)
	return a + b
end

local total = add(3, 4)
print(total)       --> 7

A function without return gives nil. return ends the function immediately, so code after it never runs.

Multiple returns and default values

A Luau function may return several values:

LUA
local function minMax(a, b)
	return math.min(a, b), math.max(a, b)
end

local low, high = minMax(9, 4)
print(low, high)   --> 4 9

Missing arguments arrive as nil, so give them defaults with or:

LUA
local function heal(player, amount)
	amount = amount or 25
	print(player, "healed by", amount)
end

heal("Ana")        --> Ana healed by 25
heal("Ben", 10)    --> Ben healed by 10

Variable arguments

... collects any number of arguments:

LUA
local function sum(...)
	local total = 0
	for _, value in {...} do
		total += value
	end
	return total
end

print(sum(1, 2, 3, 4))   --> 10

Functions are values

Functions can be stored in variables and tables, passed as arguments, and returned. This is what makes events possible.

LUA
local function applyTwice(fn, value)
	return fn(fn(value))
end

print(applyTwice(function(x) return x * 2 end, 5))   --> 20

The inline function(x) ... end has no name; it is an anonymous function.

Closures

A function remembers the local variables around where it was created. This is a closure:

LUA
local function makeCounter()
	local count = 0
	return function()
		count += 1
		return count
	end
end

local counter = makeCounter()
print(counter(), counter(), counter())   --> 1 2 3

Each counter keeps its own private count. Closures are how event handlers remember which player or part they belong to.

Events and connections

Most Roblox objects have events, signals they fire when something happens: a part is touched, a player joins, a button is clicked, a property changes. You listen with :Connect, giving a function to call:

LUA
local Players = game:GetService("Players")

local connection = Players.PlayerAdded:Connect(function(player)
	print("Welcome,", player.Name)
end)

:Connect returns a connection. Call connection:Disconnect() when you no longer need it, to stop the handler and free memory. Other useful forms:

  • event:Once(fn) runs the function a single time.
  • event:Wait() pauses the script until the event fires and returns the event's arguments.
LUA
local part = workspace.Block
local hit = part.Touched:Wait()          -- pauses here until touched
print("Touched by", hit.Name)

Event handlers run in their own thread, so a handler that waits does not block the rest of the script. The Touched lesson uses this heavily.

Errors and pcall

Errors stop a script, but some failures are normal: saving data can fail because the network drops, or a name may not exist. Use pcall (protected call) to run something risky and keep going:

LUA
local ok, result = pcall(function()
	error("the data store is down")
end)

if ok then
	print("worked:", result)
else
	warn("failed:", result)    --> failed: ...the data store is down
end

pcall returns true plus the function's result when it succeeds, or false plus the error message when it fails. You raise your own errors with error("message"), and you can assert expectations with assert(condition, "message"). Any call to a Roblox service that talks to the internet, such as data stores, should be wrapped in pcall. The data stores chapter relies on this.

The task library

Roblox's task library replaces the old wait, spawn and delay:

Call What it does
task.wait(s) Pause this script for s seconds (about one frame if omitted)
task.spawn(fn, ...) Run fn immediately in a new thread
task.delay(s, fn, ...) Run fn after s seconds, without pausing
task.defer(fn, ...) Run fn at the end of the current frame
task.cancel(thread) Stop a thread made by the above
LUA
task.delay(5, function()
	print("Five seconds passed")
end)
print("This prints first")

Use task.spawn when a part of your script needs to wait without blocking the rest, for example a countdown that runs alongside a game loop.

Stand-in: an event with Connect and Fire

Roblox events are created by the engine. This JavaScript stand-in is a small Signal class that behaves the same way: handlers are connected, fired in order, and can be disconnected or run once.

JS Stand-in: Connect, Once, Disconnect (JavaScript)

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

No output.

Stand-in: pcall, closures and defaults

JS Stand-in: pcall and a closure counter (JavaScript)

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

No output.

Style tips

  • Give functions verb names: giveCoins, spawnEnemy, isAlive.
  • Keep each function small and focused on one job.
  • Prefer local function over globals so names do not clash between scripts.
  • Return early to avoid deep nesting: if not player then return end.
  • Always Disconnect connections you created for temporary things (a round, a tool).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does :Connect return?

    Connect returns a connection object so you can stop listening with Disconnect.
  2. 2. What does pcall return when the function errors?

    pcall catches the error and returns false plus the message, so the script can carry on.
  3. 3. Which call runs a function after 5 seconds without pausing the current script?

    task.delay schedules the function and returns immediately; task.wait would pause the caller.
  4. 4. What is a closure?

    A closure keeps access to the variables that were in scope when it was made, like the count in a counter.

Summary

  • local function name(params) ... end; return sends values back and may return several.
  • Functions are values: pass them, store them, and write them inline.
  • Connect functions to events with :Connect, stop with :Disconnect, use :Once and :Wait.
  • Wrap risky calls in pcall; use task.spawn, task.delay and task.wait for timing.

Next: Tables: Lists and Dictionaries