The existence of “local” variables implies the existence of variables that are not local.
This other type of variable is the ‘global‘ variable. If local variables are limited to its active scope, then global variables do not have that restriction.
To declare a global variable, simply omit the local keyword.
Global variables must be explicitly assigned when they are declared, even if that assignment is nil.
if true then
local localVar = "Hello world!"
globalVar = 42
end
print(localVar)
print(globalVar)
--Output: nil
--Output: 42
Both of these variables are created in the scope of the if statement. The local variable no longer exists after the statement exits. On the other hand, the global variable does. This makes it possible to access that variable in other scopes.
‘Global variable’ is also used often to refer to any variable defined in the global scope of a script.
local foo = 42 --globally accessible
if true then
if true then
print(foo)
foo = foo + 3.15
end
end
print(foo)
Like the previous form, a globally scoped variable puts very little restriction on where that data can be accessed from.
Because global variables can be accessed from anywhere (within that script), any region of code can change it—including changes that you did not intend for.
This means that if you wanted to use your global variable somewhere, you now also have to take into account all the other places that variable is modified and how it affects what you are trying to do in the current block of code.
While it may seem much easier to just make all of your variables global, doing so also makes your code harder to diagnose and less modular. For simple examples, this may seem trivial but once you move on to more sophisticated scripts, becomes bug ridden.
In general, try to limit global variables to values that are not subject to be modified. So something like Pi or default game settings.
A final type of global variable with even fewer contextual restrictions are ‘_G’ variables.
These types of “variables” are not limited to the scope of a script. This means that once it has been defined, every script of the same environment (i.e. server or client) has access to that variable.
--Script 1
_G.meaning_of_life = 3.14159
--Script 2
print(_G.meaning_of_life) --Output: 3.14159
There are exceptionally few compelling reasons to use these types of variables.
If you truly do have a compelling reason, then your skill and experience is already far beyond a Roblox tutorials series so this is the extent to which we will visit the subject of _G variables.