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

How do i synchronize variables in a modulescript?

I have a modulescript under workspace:

local module = {}

function module.set(n)
	module.thing = n;
end

function module.get()
	return module.thing
end

return module

and a normal script under workspace:

require(script.Parent.ModuleScript).set(25);

When i type

 print(require(game.Workspace.ModuleScript).get())

from the command prompt, instead of giving me 25, it gives me nil.

You would think that after setting module.thing to 25 in the workspace script, requiring it from somewhere else to check the variable would be 25, but it is just the default value.

Is there a way to synchronize the variables in the module script, so I get 25 instead if nil?

2 answers

✓ Accepted answer

Every use of require does share the same module, but only within a single "client".

In particular, the command bar does not share with scripts (likely for security reasons[^1]). However, all of your Script objects will share with each other -- using _G is not necessary here (except possibly for debugging)

[^1]: although really this ought to mean they shouldn't share _G, yet they do...

I figured it out, put the require modulescript as a global variable:

_G.module = require(modulescript)

then, when you want to reference it, do this:

local module = _G.module
module.get()

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