Functions and loops, lesson 13
Scope
Goal: Know where a variable can be used.
about 5 min3 practice exercises
Where you create a variable decides where it can be used. That area is its scope.
A local variable exists from the line that creates it to the end of the block it is in. A block is the inside of a function, an if, or a loop.
local coins = 5
if coins > 0 then
local message = "You have coins"
print(message) -- works
end
print(message) -- nil: message only existed inside the if
Code inside a block can see variables from outside it, which is why the if can read coins. It does not work the other way round.
If you need a value after the block, create the variable before it:
local message = "No coins"
if coins > 0 then
message = "You have coins"
end
print(message)
Always write local. Without it you create a global variable that every part of the script can change by accident, and those bugs are hard to find.
Sources
Checked against Roblox's documentation on . The lesson is in our own words; these pages are the source of truth.