Ad
Still have questions? Join our Discord server and get real time help.
Log in to vote
0

What is the purpose for "local" in a script?

Asked by 7 months ago

why do people do

local block = script.parent

instead of just doing

block = script.parent

thanks for the help, sorry if this is a dumb question I'm not very advanced in lua.

2 answers

Log in to vote
11
Answered by
Fifkee 2017 Administrator Moderation Voter Community Moderator
7 months ago
Edited 7 months ago

You use the local keyword to ensure that your variable doesn't leave the current scope.

Scopes are like dividers for your code to run in, the mnemonic not to be confused with a function, that are blocks of code that can be called so segments of code can be ran everywhere. Everything that requires an end keyword creates a new scope for you to type your Fancy Codeā„¢ in (we don't talk about repeat). Nested scopes carry over scopes from the previous, however keywords from the current scope do not pass into a function call.

The list is: if, do, while, for, repeat, and function. All of these keywords generate a new scope.

Be mindful of what scope your code is in. If you want a variable to work everywhere in your code, place it in the toplevel. If it's a variable that only needs to work where it is in that moment then just place it inside the nearest scope, heck, just use do end.

Not using the local keyword places your variable in the global scope. The global scope is, well, what it says. It's available everywhere. It's bad practice to use the global scope as it can cause several conflicts and inconsistencies, so please use the global scope with utmost caution. Think of it like this: If you don't have the local keyword, the variable basically gets moved to the top of your code, right before anything runs.

Cheers!

0
You deserves the upvotes. Xapelize 688 — 7mo
1
Note that these conflicts, assuming you mean several threads modifying the same global variable at once causing unintended bevahior, is said to be not thread safe. hiimgoodpack 2009 — 7mo
0
i like trains iuclds 591 — 3mo
Ad
Log in to vote
0
Answered by
nc2r 120
7 months ago

In case it is in a function, if you do not use the variable out side of the enclosing function, it mutes a warning. Also, it prevents name clashes. For example:

function foo()
    local bar = 10
end
function baz
    local bar = 10
end

The above code will have both bars in each functions separate: However, in some cases, the below can be problematic, if you want the variable to be only existent in the enclosing function:

function foo()
    bar = 10
end
function baz
    bar = 10
end

But at toplevel, meaning not in a function or if statement or any enclosure, there is no difference between it being local or not.

Answer this question