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

Is "local" useful in context of the full script?

Asked by
ipiano 120
10 years ago

I've seen a lot of free model scripts start off with

local... local... local... local function...

But is that really helpful? The way I understand it, local causes the variable, or function to be local to only the context it's in; but if you start with locals that are in context of the entire script, is there really any benefit to making them local?

1 answer

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

local variables are measurably faster than global variables (measurablely, though only slightly). That's because Lua searches in the local scope first, and then the global scope, for variables.


They also act slightly differently from a global variable in their visibility:

function show()
    print(A);
    print(B);
end

local A = 1;
B = 2;

function showBoth()
    print(A);
    print(B);
end

show()
showBoth()

The output of the above will be

nil
2
1
2

since the local A is only visible to scopes defined after that position in the script.


This scope is useful since it will let you define constants at the top, but will prevent you from accidentally bleeding values in that are computed at the bottom.



It is basically up to you if you want to define things as local when they are out of all functions. Because of the previous statement, though, it can be safer to use local variables, since it's less likely variables unneeded by functions above will be accidentally used.

It could also be considered good style to always use local, since it marks the declaration and first use of a variable clearly for readers of your code (including you!)


TL;DR Use local unless it makes you unhappy (or it won't work):

  • Faster (slightly)
  • Helps catch a few mistakes
  • Easier to read
0
I thought if you used a local variable outside a function then it would work inside of one, and if you used a local variable inside a function and called it outside it would return nil? M39a9am3R 3210 — 10y
0
Local variables defined outside will work inside functions, but only for functions defined below the declaration (edited example to include that case). BlueTaslem 18071 — 10y
Ad

Answer this question