why do people do
local block = script.parent
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.
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: if, do, while, for, repeat, and 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 do end.
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.
Cheers!
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.
This discussion is preserved as it was. New answers, comments, and votes are closed.
4 comments
You deserves the upvotes.
Note that these conflicts, assuming you mean several threads modifying the same global variable at once causing unintended bevahior, is said to be not thread safe.
i like trains
… Elsa? … Do you wanna build a snowman? Come on let's go and play I never see you any more Come out the door It's like you've gone away! We used to be best buddies And now we're not I wish you would tell me why Do you wanna build a snowman? It doesn't have to be a snowman (Go away, Anna!) Okay, bye … Do you wanna build a snowman? Or ride our bike around the halls? I think some company is overdue I