Global Turtorial (_G)

Introduction of the Global
Global is _G. Basically, _G is like a module script. _G is a table so you can assign values like any other table, but _G can saves cross-script.

Example
Let’s say you have 2 different script.

First script:

local randomstring = "This line can't save across scripts" --This is the line without Global
_G.globalstring = "This line can save across scripts" --This is the line with Global

Second script:

print(randomstring) --This line will print out nil
print(_G.globalstring) --This line will print out "This line can save across scripts" and that's how Global work.

The Disadvantage of the Global
Global represents problem like altering important game state without realizing it, or attempting to access a value from it that hasn’t been set yet. Therefore, I don’t recommend people to use Global in script. Using module script is better.

Own Experience
In my experience, Global is less effcient, cause lag and is less favorable. _G is generally advised against. However, it is not technically deprecated. Performance and lag aren’t really the major disadvantages, it’s more so that it isn’t guaranteed to exist when you access it. My example demonstrates this, since it may or may not print nil whenever it’s run, depending on which script is run first.

This leads to bad code, often needing messes like this whenever _G needs to be accessed:

repeat wait() until _G.whatever
5 Likes

This is inaccurate. _G is generally advised against, but it is not technically deprecated. Performance and lag aren’t really the major disadvantages, it’s more so that it isn’t guaranteed to exist when you access it. In fact, your example demonstrates this, since it may or may not print nil whenever it’s run, depending on which script is run first.

This leads to bad code, often needing messes like this whenever _G needs to be accessed:

repeat wait() until _G.whatever
5 Likes

O. I learned more about Global. Thanks for your answer.