Scopes
Scopes are what define the range of functionality to a variable or function. This specifically applies in Lua to local variables & functions. When you define a variable or function with local, its scope is defined by the innermost block of code you define it in.
Example of various scopes:
1
local x = 15 -- scope is script-wide, x can be accessed anywhere inside of this script
2
​
3
function a()
4
local first = true -- first can only be accessed throughout a()'s code block
5
if first then
6
local second = 123 -- can only be accessed within this if statement
7
print(second) -- Output: 123
8
end
9
print(second) -- nil, cannot access that variable anymore
10
print(first) -- Ouput: true | we can access this variable since we're still inside of the function's code block
11
end
Copied!
Another example showing a function's scope:
1
local function outputTable(t)
2
local function output(t)
3
for k, v in pairs(t) do
4
print(k, v)
5
end
6
end
7
output(t) -- output function is only accessible inside of outputTable
8
end
9
​
10
outputTable({1, 2, 3}) -- works, outputTable's scope is script-wide
11
output({1, 2, 3}) -- will return an error, output is inaccessible since it's not inside the current scope, it is inside of outputTable.
Copied!
​
Last modified 2yr ago
Copy link