Functions and loops, lesson 11
Functions
Goal: Name a block of code and run it when you want.
about 5 min3 practice exercises
A function is a named block of code you can run whenever you want. You define it once and call it by name.
local function celebrate()
print("Coin collected!")
print("Nice one")
end
celebrate()
celebrate()
Lines 1 to 4 only define the function. Nothing prints until line 6 calls it with celebrate(). Calling it twice prints the two messages twice.
Functions matter for two reasons:
- No repeated code. If the celebration changes, you change it in one place.
- Names explain intent.
celebrate()tells the reader what happens without reading the lines inside.
You have been calling a function since lesson 1: print is a function that Luau gives you.
Sources
Checked against Roblox's documentation on . The lesson is in our own words; these pages are the source of truth.