Why do people use local variables in the main scope? For example (taken from the LMM Admin script):
local Bet = SettingsModule.Bet or " "
But wouldn't the following do the exact same thing even shorter?
Bet = SettingsModule.Bet or " "
Declaring variables locally places them on the stack instead of in the memory so they can be referenced more quickly. It's for the sake of efficiency; it saves a lot of time if you're referencing a variable thousands of times and it can be accessed more quickly.
1waffle1 is right, they are faster to reference and more efficient to use. Usually, though, this is negligible.
Still, there are differences between a local variable at the top and a global variable.
For instance, consider the following:
function fun() print(a,"fun"); a = 2; end a = 1; fun(); print(a,"main");
The output of this program will be
1 fun 2 main
Most likely, that is not what you desired to write. If we make a
local
, however, we get the solution where a
is not randomly affected by a call to a function:
nil fun 1 main
For this reason, it is slightly safer & simpler to use local variables in the main scope, too, when the variables are not meant to be manipulated directly by any sub functions (although this does not solve the problem if a
were declared before fun; it at least makes it slightly easier to avoid errors).
well wat I know is if u for example are using a Player Picker then u'd want to do;
local SpecialPlayer = math.random(#Player, 1)
so then if it's a Player Picker and ur trying to tell the system wats his Name is, so u say local and then u can use the Name in later lines inside the same Script faster, just like them 2 guys said above. I guess this is not much help but I always love trying to help people :D
Marked as Duplicate by Scripting Helpers
This question has been asked before, and already has an answer. If those answers do not fully address your question, then please ask a new question here.
Why was this question closed?