Global Variable

Learn and how to use it.

by GabrielDeaf

Author Avatar

Today we are going to use global variable instead local variable.

Global variable can be access everywhere for script, instead just one script for local.

Below, you will see how to use.

--First Script in FirstPart Model

_G.a = "Hello Global!"


--Second Script in Second Part Model

print(_G.a)


--Output: Hello Global!

If you use the Local, then it won't work for both script, just one.

--First Script in First Part Model
local a = "Hello Global!"

--Second Script in Second Part Model
print(a)

--Output: Unknown variable in Second Part Model: Line 1 (a)

Global variable can be useful for Leaderboard like upgrade in Obby. Example below:

--A script in Game.Workspace

game.Player.PlayerAdded:connect(function(plr)

   _G.stats = Instance.new("BoolValue", plr)

   _G.name = "Leaderstats"


   _G.level = Instance.new("IntValue", _G.stats)

   _G.level.Name = "Level"

   _G.level.Value = 1

end)

--------------------------------
--A script in Game.Workspace.Part
--When the player hit the part, the player leveled up. The following code will be below
_G.level.Value = 2

And lastly, I will be still adding some stuff here to make it easier. Thanks all!

View in-game to comment, award, and more!