Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

✓ Accepted answer

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

2 comments

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?

0

Local variables defined outside will work inside functions, but only for functions defined below the declaration (edited example to include that case).

This discussion is preserved as it was. New answers, comments, and votes are closed.