why do people do
instead of just doing
block = script.parent
thanks for the help, sorry if this is a dumb question I'm not very advanced in lua.
You use the
local keyword to ensure that your variable doesn't leave the current scope.
Scopes are like dividers for your code to run in, the mnemonic not to be confused with a function, that are blocks of code that can be called so segments of code can be ran everywhere. Everything that requires an
end keyword creates a new scope for you to type your Fancy Code™ in (we don't talk about repeat). Nested scopes carry over scopes from the previous, however keywords from the current scope do not pass into a function call.
The list is:
function. All of these keywords generate a new scope.
Be mindful of what scope your code is in. If you want a variable to work everywhere in your code, place it in the toplevel. If it's a variable that only needs to work where it is in that moment then just place it inside the nearest scope, heck, just use
Not using the
local keyword places your variable in the global scope. The global scope is, well, what it says. It's available everywhere. It's bad practice to use the global scope as it can cause several conflicts and inconsistencies, so please use the global scope with utmost caution. Think of it like this: If you don't have the
local keyword, the variable basically gets moved to the top of your code, right before anything runs.
In case it is in a function, if you do not use the variable out side of the enclosing function, it mutes a warning. Also, it prevents name clashes. For example:
function foo() local bar = 10 end function baz local bar = 10 end
The above code will have both bars in each functions separate: However, in some cases, the below can be problematic, if you want the variable to be only existent in the enclosing function:
function foo() bar = 10 end function baz bar = 10 end
But at toplevel, meaning not in a function or if statement or any enclosure, there is no difference between it being local or not.