What is shared and how i can use it

Hi!
Today i have question, what is shared and how i can use it?
Can someone explain about it? Thank you!

5 Likes

shared is like _G. It is shared across scripts. And you don’t use it for this very reason. Your code should instead be more modular by nature.

3 Likes

You can read more info on it here: Roblox Globals | Documentation - Roblox Creator Hub. Shared is basically a global table that can be referenced from any script and it allows you to defined Global variables locally or on the server. It is recommend you don’t use the shared table unless you know what you are doing, it is much better to use module scripts because they can do the same thing.

3 Likes

can i use shared for store remote event ?
like

another script
shared.moneyremote = game.whereisremoteevent
another script2
shared.moneyremote:FireServer()

can i do like that?

But why are using it for that?

i just wanna make it shorter…

You should be using a local variable in that example and not a global one, imo there is no reason for the global environment to ever be used on roblox.

2 Likes

uhh i mean not same script…

Yeah I figured so, but it is still bad practice, because you can’t control the order in which the two scripts will run, for example, if the script where you call shared.moneyremote:FireServer() loads before the script where you set the global variable it is going to cause an error, which is why you should not use it unless you can guarantee that the global variables will all be set before they are referenced.

1 Like

all of my script none of it called FireServer() if useless.
uhhh i mean i guarantee none of it called before it got set

I’m not sure what your saying, but you should not using it for that, don’t be lazy and just define the remote event wherever you need to use it.

1 Like

But how do you guarantee that? You can’t control the order in which your code will run unless you use a strictly modular framework and only have one server and client script that load in the core modules in the desired order.

ok, thank you
but shared will do not replicated to server/client right?

if set on server it will do not replicate to client
if set on client it will do not replicate to server right ?

Yes it will not replicate, it will only work in the environment it is defined from.

ok, thank you very much for your help.

your old answer are defined as solution