There are local variables that I've learned about, but I have never heard a single mention of how to make a global variable. This would be very useful when I need to call onto the same thing many times within different scripts. Is that even possible?
A global variable is simply one defined without the local
keyword. It can be accessed in any scope, unlike a local variable:
do local LocalVariable = 1 GlobalVariable = 2 print(GlobalVariable) --> 2 print(LocalVariable) --> 1 end print(GlobalVariable) --> 2 print(LocalVariable) --> nil
It is generally prefered to use locals over globals as they perform better and prevent unwanted side effects from accidentally overwriting globals defined in other scopes.
If you want to access one variable or function from different scripts, there are two options. The preferred option is using ModuleScripts.
The other option is to use the _G
variable, like this:
_G.MyNumber = 5 function _G.MyFunction() end
The contents of _G
can be accessed by any script. Note that there is a separate _G
for the server and for every client, so local scripts cannot access the contents of the server's _G
.
_G. is global variables but there are 2 sides to it, there is server global variables and local global variables which are different. server meaning if you created the variable using a server script only server scripts can use that. but if you created the global variable using a local script only local scripts can use that variables. so if you had created a variable from a server script and tried using a local script for that server global variable it would just return nil or in other words it just wouldn't exist and error your script. here are a couple examples.
_G.Number = 0 _G.Bool = true _G.String = 'Hello world!' _G.Function = function() -- same as below but written slightly different (personal preference) end function _G.Function() -- same as above but written slightly different (personal preference) end _G.Table = {_G.Number, _G.Bool, _G.String, _G.Function} -- creates a table/array of all the values we just set, this is just to show how you would get the variables, basically the same way you wrote them. local Number = _G.Number local Bool = _G.Bool local String = _G.String local Function = _G.Function local Table = _G.Table -- This ending part shows how you would create a local variable from all the global variables that we had set. If you have any question or if this wasn't what you were talking about you are free to send me a private message or just comment on this answer. Thank you!