Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

When should i know to use 'local' in variables?

people tell me i should put local in front of my variables but why

5 comments

2

it's just better practice

0

Yep it's just better practice

0

does it actually make a difference tho?

0

See Variables on RobloxDev or Lua website. Deals with scopes.

0

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.

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.