So for the past few years, I’ve been using “local” on everything… Even before any events/control structures start.
local Time = 30
I am aware of the use in a function/control structure that it limits the scope, but if it is on the top of the script, is it 100% necessary to declare the scope since its “local” to the entire script…
I have always heard that you always want to use local before any variable, not mattering if it needs to be declared or not… Yet in all “beginner” tutorials on Variables, its always ignore the local.
So is it really needed or is it more of a preference to put it?
I don’t remember the exact number, but there is a performance boost that comes from localizing your variables, even your “global” variables. If I remember correctly, it’s due to the fact that it’s much easier performance-wise to index a smaller table, or something along those lines.
There’s nothing really forcing you to localize your global variables, but it’s generally good practice. The thing that makes it good practice is that everybody else is doing it. It’s always good to do what everybody else is doing, it makes working with teams so much easier, and it makes your code more maintainable.
People say to use local variables simply because it is “faster”, which is true, however specifically globals exist outside of the stack and have to be loaded into it when they are called (extra instructions internally). Locals exist in the stack by default. Really, it is a micro-optimisation, however given the fact that Roblox scripts do not share the same environment, globals provide no real benefit since you are unable to access them from a different script environment (they are acting pretty much as locals because of this except being loaded into the stack when you call them).
Other than above, there is no real difference outside of scoping.
These are bad tutorials. Explaining how and when to use local variables is an important part of learning to script. Like other people have said, localizing your variable gives a tiny performance boost, but, more importantly, it can be used to localize a variable to within a function. I know you know about scope, but these “beginner tutorials” should be using local variables and explaining how they’re different (and generally better).
In addition to the scoping benefits, there is a performance benefit as globals are stored in a global table _G (at least, in 5.1.x, although the situation is similar 5.2-), whereas locals are written to a register so are faster to look up. However, this lookup is typically insignificant, unless you are using lengthy iterations (a typical example is redeclaring math methods before a loop if you are going to have lots of iterations).
Other than this, it’s good practice to use local when initially declaring a variable, to make it clear that a new variable is being introduced.