Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
7

Why do people use local variables in the main scope? [closed]

Asked by
gskw 1046 Moderation Voter
10 years ago

This question already has an answer here:

"local" in front of variables

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 " "
0
+1 for asking this 1waffle1 2908 — 10y

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?

3 answers

Log in to vote
8
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
10 years ago

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.

Ad
Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

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).

Log in to vote
-2
Answered by
KAAK82 16
10 years ago

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