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 User#22980 0 — 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.
01for i = 0, 10 do
02    local x = i;
03end
04 
05print(x); --nil
06 
07for i = 1, 100 do
08    local y = i + 100;
09end
10 
11print(y); --nil

Even if you really wanted to use global variables, you could simply declare local variables at the beginning of your script....

01local x = 0;
02 
03while x < 10 do
04    x = x + 1;
05end
06 
07print(x); -- 10
08 
09while x < 100 do
10    x = x + 1;
11end
12 
13print(x); -- 100
14 
15while x < 50 do
View all 21 lines...

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