Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 6 years ago

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

2
it's just better practice ScrubSadmir 200 — 6y
0
Yep it's just better practice MrGaming4me 28 — 6y
0
does it actually make a difference tho? Metraria 17 — 6y
0
See Variables on RobloxDev or Lua website. Deals with scopes. xPolarium 1388 — 6y
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. User#24403 69 — 6y

1 answer

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

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.

0
should i always use local even if its outside of functions and stuff? Metraria 17 — 6y
0
Of Course. Hope this answers your question. zafiruatest 75 — 6y
Ad

Answer this question