Luau Functions Explained With Roblox Examples
Learn how to write local Luau functions, return multiple values, use colon methods with self, pass callbacks, and handle variadic arguments.
- Difficulty
- Beginner
- Time Needed
- 15 To 20 Minutes
- Recommended Declaration
- local function camelCaseName(param1, param2)
- Missing Arguments
- Receive nil Automatically (Extra Arguments Are Ignored)
- Method Call Syntax
- Colon (:) Passes self Automatically As First Argument
- Variadic Token
- ... As Final Parameter (Distinct From .. Concatenation)
Define Local Functions And Handle Parameters Safely
Functions bundle reusable Luau logic into named blocks that can run on demand, respond to Roblox events, or live inside ModuleScripts shared across multiple scripts. Declare helper functions with local scope and camelCase names—such as local function calculateReward(baseCoins, multiplier)—so they remain fast and scoped cleanly to the current script.
Luau is forgiving about argument counts when calling a function, which creates a classic beginner trap. Passing extra arguments simply discards the leftovers, while passing fewer arguments than listed fills every omitted parameter with nil. Performing math directly on a missing parameter throws an arithmetic error, so assign fallback defaults inside the body—such as local mult = multiplier or 1—whenever a parameter is optional.
Return Single Or Multiple Values From A Function
A function that reaches end without hitting return outputs nil. Adding a return statement hands one or more computed values back to the caller, and Luau lets a single function return multiple comma-separated values at once—for example, return total, hasBonus. Capture both results on the receiving line with local payout, gotBonus = calculateReward(50, 2).
Keep one strict parser rule in mind: return terminates the function immediately and must be the final statement inside its block. Writing extra lines directly after return inside the same block causes a syntax error; place early exits inside an if ... then return end block instead.
Understand Colon Methods And The Self Parameter
Many beginners encounter errors when mixing dots (.) and colons (:) on Roblox objects such as part:Destroy(), part:Clone(), or model:FindFirstChild(). Methods are functions stored on an object or table that expect the owning object itself—named self—as their very first argument.
Calling object:Method(arg) is syntactic shorthand for object.Method(object, arg), automatically supplying self without repeating the variable name. The exact same rule applies when building custom tables: defining function RewardBank:addCoins(playerName, amount) injects self implicitly, making it identical to RewardBank.addCoins = function(self, playerName, amount).
Connect Event Handlers Callbacks And Anonymous Functions
Because functions are standard Luau values, you can pass them straight into other functions or hook them up to Roblox signals. Connecting a named handler like Players.PlayerAdded:Connect(onPlayerAdded) runs onPlayerAdded every time a player enters. Never add parentheses inside Connect—writing Connect(onPlayerAdded()) executes the function immediately during script startup and passes its nil return value instead of the function reference.
When a tiny handler is only needed once—such as inside task.delay(2, function() ... end) or a table.sort() comparator—use an anonymous function without a name (anonymous functions always have local scope automatically). Note also how Roblox callbacks such as BindableFunction.OnInvoke or RemoteFunction.OnServerInvoke differ from events: a callback accepts a single assigned function via = and yields until that function returns a value back to the caller.
Accept Flexible Inputs With Variadic Functions
Built-in utilities like print() and string.format() accept any number of inputs because they are variadic functions. You can write your own by placing three dots (...) as the final parameter—not to be confused with the two-dot (..) string concatenation operator.
Inside the function body, ... cannot be indexed directly like an ordinary variable, so pack it into a table using local items = { ... } or forward ... straight into another call. Also remember that a nested function defined inside a variadic function cannot access the outer function's ... directly; pack the arguments into a local table first if an inner callback needs them.
Build A Player Reward Script With Luau Functions
Insert a Script inside ServerScriptService, paste the Luau code below, and start a playtest with F5. The example ties together a custom table method using colon notation and self, a multi-return reward calculator with an optional multiplier default, a variadic log formatter, a named PlayerAdded event handler, and an anonymous task.delay callback.
local Players = game:GetService("Players")
local RewardBank = {
balances = {} :: { [string]: number },
}
function RewardBank:addCoins(playerName: string, amount: number): number
local current = self.balances[playerName] or 0
local updated = current + amount
self.balances[playerName] = updated
return updated
end
local function calculateReward(baseCoins: number, multiplier: number?): (number, boolean)
local mult = multiplier or 1
local total = baseCoins * mult
local hasBonus = mult > 1
return total, hasBonus
end
local function logSummary(prefix: string, ...)
local entries = { ... }
print("[" .. prefix .. "]", table.concat(entries, " | "))
end
local function onPlayerAdded(player: Player)
local payout, gotBonus = calculateReward(50, 2)
local newBalance = RewardBank:addCoins(player.Name, payout)
logSummary("REWARD", player.Name, "Payout=" .. tostring(payout), "Bonus=" .. tostring(gotBonus), "Total=" .. tostring(newBalance))
task.delay(2, function()
print("Welcome bonus verified for " .. player.Name)
end)
end
-- Pass the function reference without parentheses
Players.PlayerAdded:Connect(onPlayerAdded)