How in the world do local variables work?

I don’t have any idea on how local variables work. The Developer Hub isn’t very clear on how it works. Here are my questions:

  • Do these variables have to do with certain things happening for certain players?
  • Are local variables related to LocalScripts in any way?
  • According to the Developer Hub, local scripts are assigned to the code blocks that declare it. What does this matter?

I’m sorry if any of these questions should be painfully obvious, I’m still learning.

no

Local variables can only be used in the scope they are declared in.

do
    local x = 10
    print(x) -- 10
end

print(x) -- nil

It is good practice to use local variables for this reason.

5 Likes

Local variables have their scope limited to the block where they are declared. A block is the body of a control structure, like for an example, if you declare a local variable inside a function, you can’t get the value from it outside that function.

This also apply if it’s declared inside an if block, do-end block or inside the loops(Like while-do-end, for-do-end and repeat-until).

2 Likes

So what’s the point of using them? They seem to be just normal variables but you can’t access them in other places.

local makes variables respect “scopes”. Scopes are like parts of code where a start and end are given. For example, If/Then statements create a scope.

if _ then

end

This creates a scope between THEN and END. Programmers use tabs or spaces to indent code, to visually show scopes. The scope starts at THEN and ends at END. Any variables CREATED inside the scope, will be deleted whe the scope ENDS. incapaz’s example of creating a local variable inside of a scope and trying to access it outside is a good example of what happens.

1 Like

If you have a huge script then it’s good to limit the amount of variables to reduce complexity, memory and improve performance

2 Likes

They are faster to get value from compared to global variables (Around ~10% faster compared to globals.).

2 Likes

You should always use local variables. In my example if the variable x was global then it would escape the scope and print 10 in both places. This is bad since it pollutes the global environment and makes you more prone to name collisions. There is also that negligible speed boost.

3 Likes

So, just to make sure I understand, it can let a variable have 2+ different values in the same script, and it’s also a performance booster?

A variable can only contain one value, the point is what if you end up needing to reuse the same identifier but not the same variable itself. And yes local access is slightly faster than global since the former grabs from the stack whereas the latter grabs from the environment.

4 Likes