Local and Global variables

What is the difference between Global variables and Local variables? I think Global Varianles are variables which can be accesed by the entire script, but, if so, then why do people even use local variables?

Local variables are obtained faster than global variables

It’s bad practice to use global variables since there slower, I don’t really see any need for using them really. So the way it works is local variables can also be used by the whole script if the variable is created outside of a function.

local function RandomFunction()
   local NewVar = true
end

print(NewVar) -- nil

NewVar will not print outside of the function since it’s local to the function whereas global variables can be used anywhere

local function RandomFunction()
   NewVar = true
end

print(NewVar) -- true

Now I would recommend doing this instead of using global variables:

local NewVar -- Empty Var | Outside the function
local function RandomFunction()
   NewVar = true 
end

print(NewVar) -- true

Hope this helps!

1 Like

Ty! I always wondered why people use local variables when they could’ve used global, now I know!

1 Like