Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How could I define a variable as a global?

Is this even possible in ROBLOX?

Say, I want to define player in one script, is there a way to access it in another?

Example:

player = script.Parent.Parent

Where as later, I want to use player again, would I have to redefine it?

1 comment

0

Hmm. Several possible answers for a better way to do that, but not knowing much about what you're doing, I can't say what is the best option. You could use an IntValue object (or whatever type you need), or you could put the code in a module script, or you could take all the code that needs that variable out of their current scripts and put them all in one script.

1 answer

✓ Accepted answer

_G

There is a global table called _G shared between each side of the network (Client / Server). For clients, this table is private for that specific machine. Other clients do not share the same _G table. On the server, this table may be shared between any server script.

Problems retrieving global variables

Even though you may have written a value to _G in one script, that doesn't mean it's up and ready to use before another script that wants to index it. Because of this, in situations where you're uncertain of which instruction will run first, it's wise to wait for a variable to read from in _G. Here's an example:

Script A

_G.Test = "Hello world"

Script B

while _G.Test == nil do wait() end -- Create a loop that will keep the script running this check until the value you're looking for exists.

print(_G.Test) -- Then print it.

Hope this helped, let me know if you have any questions. I also recommend checking out this link: http://wiki.roblox.com/index.php?title=Function_dump/Basic_functions#G

2 comments

1

Just keep in mind that this won't work for communicating variables between the client and server.

0

Also, you probably shouldn't use global variables. Whatever it is you are doing, there is a better way of doing it. Using Value objects, for example.

This discussion is preserved as it was. New answers, comments, and votes are closed.