Using module scripts to share variables

I’m trying to organize my game code into module scripts, but many of these share variables that I don’t want to send as arguments through function calls to keep things simple. Ideally I just want to have a globalvars module script that other module scripts can read and write variables to; however my attempts have failed. For example, Script A sets a variable in the globalvars module script, but when Script B reads it, the variable returned is its default value instead of the updated one. I thought I could do this many years ago, but I’ve forgotten.

Here’s my attempt.

globalvars module script:

local vars = {
    ["scaleUpFactor"] = 1
}

local module = {}
module.SetVariable = function(varName, newValue)
    vars[varName] = newValue
end

module.GetVariable = function(varName, newValue)
    return vars[varName]
end

return module

Script A:

local GlobalVars = require(ScriptFolder:WaitForChild("globalvars"))
GlobalVars.SetVariables("scaleUpFactor",4)

Script B called after Script A:

local GlobalVars = require(ScriptFolder:WaitForChild("globalvars"))
print(GlobalVars.GetVariables("scaleUpFactor"))

Output: 1
Expected Output: 4

2 Likes

So I believe I solved my own problem. I had an unrelated issue which made it appear as if the code above did not work, but it actually does output 4 as expected. I’ll just leave this here incase anyone needs it.