Is there a way to make a variable global across all scripts?

I want to make a variable “global” across all scripts. For example, script1 makes a variable and makes it global, and script2 can access that variable. Is there a way to do that?

1 Like

You can use shared:

shared.Foo = "ooo"

In another script:

print(shared.Foo)

Read more about it here.

4 Likes

Use shared or _G, they’re tables.

shared.hi = "hello" --my personal choice since the underscore is hard to reach
_G.bye = "bye"
4 Likes

I tried with _G and shared and both times it printed nil, I didn’t make any typos or anything

Edit: Nevermind, it was just me being stupid. I did print(hi) in the other script when I should have done print(shared.hi)

2 Likes

This is why it’s important to show your attempts when writing threads, so that the actual issue can be addressed rather than having to speculate what you’ve tried already and what does or doesn’t work.

On another note: a script defining something in _G/shared isn’t guaranteed to run before another script that requires that variable, so you should include a loop that waits for the variable to be defined.

while not _G.something do wait() end

That being said, you could just use ModuleScripts to avoid loops, globals and unpredictable code execution times and you never really should be using globals in your scripts in the first place. On Roblox, they have little to no utility.

6 Likes

Which is more reliable, or is it just down to personal preference?

You can use IntValues, and stuff like that.

1 Like