✓ Accepted answer
Hey Typical,
Local allows things to be defined in a different scope. In programming, a scope defines accessibility. Everything in your script is inside of a scope, and the variables which you address all depend on the scope in which they are.
Local limits the scope of a variable and makes it only be defined in that local scope. While not declaring a variable as local will allow it to be accessible through the entire script. It is standard practice to declare pretty much all variables locally, as it can help preserve memory, and allows you to use this idea of scope as a feature.
####Example: Local Variables
local a = 3
function sum(b, c)
return a + b + c
end
function subtract(b)
return b-a
end
print(a + b + c)
###Now here, b and c are only within the scope of the function sum. Even though they are not defined as local, all parameters are within the scope of their respective functions.
###However, a is defined within the scope of the entire function. That is why it can be used both within sum and subtract.
###Essentially, local functions follow a similar rule:
####Example: Local Functions
local function sum(a, b, c)
local function subtract(a, b)
return b-a
end
subtract(2,1)
return a + b + c
end
sum(1,2,3)
subtract(2, 1)
###Above is just an example of using local functions and both of the local functions are defined within their own scope. Keep in mind, the function sum can be accessed anywhere within the script, including within itself. That is more of the idea of recursion.
##Here you can learn more about scope.
Best regards,
Idealist Developer
5 comments
You mean local variables.They are basically the same as globals, the only real difference is that local variables may be a bit faster than variables without local
Local functions are not the same as local variables. Local functions are functions that run in its own scope
here's a source for you: https://scriptinghelpers.org/questions/6/local-in-front-of-variables
Local variables also run in their own scope
yea, i meant to say that too.