Why is it always better to write 'local' before creating a variable?

I see many devs on YouTube keep saying always use local when creating a variable, and I still don’t get why that is important.

Why is it so? What would happen if I didn’t write local before variables?

Thanks in advance!

8 Likes

It is recommended to do so because local variables are what scripts run best with. Putting local in front of your variable name just describes its scope. If you don’t put local, it makes the variable global. Global variables can be used by any part of the script, rather than with local variables, which only that specific block can use it. It is not recommended to use global variables as it tends to make the script run slower and it is just overall better to use local variables instead of global.

Hope this helped! :slight_smile:

7 Likes

you can use global variables anywhere in the script, but local is only usable in the local scope

lua uses a global table to store global variables, so writing and reading from it is usually slower

6 Likes

I finally get it after months of confusion. Thank you :slight_smile: :slight_smile:

5 Likes

You’re welcome! Have a wonderful day! :slight_smile:

3 Likes

Thank you too! Wish I could mark two posts as the solution.

3 Likes

Quick question.

You said that local variables can be only accessed by a specific block, but I found out that I can use it anywhere in the script if it’s created outside a function, if statement, event, etc.

If it’s created on the first lines, I could use it anywhere else.

How??

3 Likes

By the way I understand it, when creating a variable outside of a function, if statement, or event, it is basically equivalent to making the variable global.

3 Likes

Even if it’s a local variable?

2 Likes

By the way I understand it, yes.

[char limit]

2 Likes

That’s a bit confusing, ngl.

But I get it. :+1:

2 Likes

Yeah, it is lol. Any other questions?

2 Likes

Not at the moment :+1: ‎ ‎ ‎ ‎ ‎

2 Likes

All right, have a good night!

[char limit]

3 Likes

I had a nightmare where none of my variables were local. Worst one so far.

4 Likes

You mean you created a whole game without localizing all of the variables in it?

4 Likes

I wrote something complicated and it would only work for one person because everything was global. Nothing was defined in the highest scope. It was like this:

Event1:Connect(function(A)
    Hello = A
end)

OtherEvent:Connect(function(B)
    -- `Hello` is `nil` until `Event1` is fired 
    print(Hello, B)
end)
4 Likes

Oh I get it. ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎

4 Likes

you can use local variables on anything inside of the scope

if you put it at the top of the script outside of everything, then everything in the script is inside of the scope so you can use it anywhere

2 Likes