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!
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!
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!
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
I finally get it after months of confusion. Thank you
You’re welcome! Have a wonderful day!
Thank you too! Wish I could mark two posts as the solution.
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??
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.
Even if it’s a local variable?
By the way I understand it, yes.
[char limit]
That’s a bit confusing, ngl.
But I get it.
Yeah, it is lol. Any other questions?
Not at the moment
All right, have a good night!
[char limit]
I had a nightmare where none of my variables were local. Worst one so far.
You mean you created a whole game without localizing all of the variables in it?
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)
Oh I get it.
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
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.