Global Variables

Hello! I’m kind of curious as to what global variables are, what they do and in what situation i should use them.

Could somebody explain it to me?

6 Likes

Global variables are variables which can be seen from all scopes of a script.

It’s useful for when you want variables that can be seen in ALL parts of a script rather than just a function/loop etc.

For example

testVar = 1

for i = 1, 10 do 
    testVar = testVar + 2
    print(testVar)
end

print(testVar)

It’ll basically print > 21

However, if you do

local testVar = 1

for i = 1, 10 do 
    local testVar = testVar + 2
    print(testVar)
end

print(testVar)

It should end up printing the initial variable, which was > 1

5 Likes

Wait, so a global variable is literally just;

local GlobalVariableName = 1

if workspace then
GlobalVariable = 2
end

?

1 Like

There are these types of global variables:

Although people often say “Global Variable” when they refer to variables that can be used anywhere throughout the script. (See @Aldanium’s post.)

25 Likes

You’re using two different variables there. “GlobalVariableName” and “GlobalVariable”

A global variable is just to be able to use that variable in other parts of the script in order to change it or get it and then be able to use it further down in the script ( as mentioned, to access from all scopes of a script )

Local variables are just used to change or get variables inside a function and/or a loop.

3 Likes

Oh true, my bad, I meant to name them both “GlobalVariableName”

Another form of global variable uses _G like @polill00 said, that is used to be able to access the variable from different scripts.

3 Likes

Are there any limits to _G variables or?

2 Likes