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?
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):