Hello developers. Are variable I declare in a script (that isn’t local) able to be used across every server script?
Edit: For example…
hello = script.Parent
Hello developers. Are variable I declare in a script (that isn’t local) able to be used across every server script?
Edit: For example…
hello = script.Parent
No you can use it in every part of a script but not in every script of the game.
The short answer is no, even if you do this
var = 10
instead of
local var = 10
It will still only be seen by the script that declared it. If you want something to only be seen by server scripts, you can prefix it with _G.
or make a modulescript that only server scripts use
Do you mean like this?
_Gvar = 10
What is a modulescript?
Do you mean blocks? I have heard that term used before but aren’t too sure what it means.
_G.var = 10
is what I meant, I’ll have to test that out to see if it does what it’s meant to do
ModuleScripts are just containers of functions and variables that can be required by any script for when you need to use something that’s in that ModuleScript, it’s mostly to prevent code repetition if you need to use the same function or variable in many places for example
So are the scripts requiring the ModuleScript a child of it or something?
For example a local variable
game.Players.PlayerAdded:Connect(function(player)
local var = 10
var = 50 --you can use it here
end)
var = 5 --you cannot use it here
If you use a global variable you can do var = 5
out of the function.
I see now, so what is the point of creating global variables inside functions if you can just create them outside of them (if there is any)?
I think in your case you can use _G.
, I used these 2 scripts with this code in them
_G.var = 10
wait(1)
print(_G.var)
And even though the other script didn’t know about var, it still printed 10
Also modulescripts are just scripts like regular scripts and local scripts that can only be used when you require them. Say you have a ModuleScript in ServerStorage with this code
local module = {}
module.Var = 10
return module
And to get that you just require the module and reference the Var
thing from another script
local module = require(game.ServerStorage.ModuleScript)
print(module.Var)
The difference between _G
and ModuleScripts is that _G
variables are only seen by either the client or the server, depending on wher eit was made. If you made _G.var = 5
in a regular script, Localscripts will not be able to see that var is globally 5, but ModuleScripts can be required by both regular and local scripts
You may want to create the variable only after a certain condition occurs and if you want to use it outside of that function you can.