Intermediate
Free
Functions
If you find yourself copying and pasting the exact same code in multiple places, you are doing it wrong. Use Functions to write reusable blocks of code.
Defining a Function
A function is like a recipe. You write the recipe once, and then you can "call" it as many times as you want to bake the cake.
local function WelcomePlayer()
print("Welcome to the game!")
end
-- To run the code, you must "call" the function:
WelcomePlayer()
Parameters & Arguments
Functions become powerful when you give them data to work with. These pieces of data are called Parameters.
When writing modern Luau, you should use Strict Typing (name: string) to tell the script exactly what kind of data the parameter should be. This gives you amazing autocomplete features in Studio.
local function DamagePlayer(playerName: string, amount: number)
print(playerName .. " took " .. amount .. " damage!")
end
-- Calling with arguments
DamagePlayer("ekian", 25)
Return Values
Functions don't just execute code; they can also calculate a result and return it back to wherever the function was called.
local function AddNumbers(a: number, b: number): number
return a + b
end
local result = AddNumbers(10, 5)
print(result) -- Prints 15