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

How do i use the same variable in different scripts?

I dont really understand variable scopes in Roblox Lua so I would like some help with it. When i create a variable, and then try to use it in Another script, i get a error saying "Unknown global"

Script A

var = 3 * 3 --- I set the variable

Script B

print[var] --- I try to use the variable but i get the error.

I would appreciate an explanation on how the scopes work in Roblox Lua and how i make a variable that i can use on all my scripts. Thanks!

2 answers

###No, don't use _G to make global variables. Use module scripts instead.

-- Place this module in ReplicatedStorage

local module = {}

module.stringthatsayshi = "hi"

function module:printstring()
    print(self.stringthatsayshi)
end

return module 

###From a server/local script:

local module = require(game:GetService("ReplicatedStorage").ModuleScript)

module:printstring()
_G.var = 3*3

This will allow you to use this variable in any script aslong as you put "_G." before it.

print(_G.var) 

Will print 9

4 comments

0

I think it worked but im using the _G. variable in a weapon and the weapon just stops working completely when i set the BaseDamage variable to my _G.damage variable

0

Use a remote event and have a local variable for gun damage,pass the damage over from client to server and then you can access it

0

Will you give me some code for that? juist so i understand better. Im currently using a remote event that gives the player "Strength" when shooting the gun. And i guess i could do something similar?

0

Dm me on discord itll be easier

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