people tell me i should put local in front of my variables but why
COMMUNITY QUESTION
When should i know to use 'local' in variables?
1 answer
local variables is deemed to be a better practice because:
- It is just a better practice
- Avoids Name Collision
- Belongs to only certain chunk, depending on where you define it.
for i = 0, 10 do
local x = i;
end
print(x); --nil
for i = 1, 100 do
local y = i + 100;
end
print(y); --nil
Even if you really wanted to use global variables, you could simply declare local variables at the beginning of your script....
local x = 0;
while x < 10 do
x = x + 1;
end
print(x); -- 10
while x < 100 do
x = x + 1;
end
print(x); -- 100
while x < 50 do
x = x + 100;
end
print(x); -- 100.
-- while (100 < 50) is not true. The loop never initiates.
Unless there are specific scenarios where it is an absolute requirement.
2 comments
0
should i always use local even if its outside of functions and stuff?
0
Of Course. Hope this answers your question.
This discussion is preserved as it was. New answers, comments, and votes are closed.

5 comments
it's just better practice
Yep it's just better practice
does it actually make a difference tho?
See Variables on RobloxDev or Lua website. Deals with scopes.
Global variables make your codebase a mess. They also pollute the global namespace as well as increase the risk for a name collision. Then there are no more variable names.