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

Module script usage?

How do you make a variable work between scripts using module scripts?

1 answer

✓ Accepted answer
--ModuleScript (in ReplicatedStorage if you want to use LocalScripts to require it, ServerScriptService otherwise)

local module = {}
module.sharedVar = 27 --Anything inside this table is accessible to things that require() this module.
hiddenValue = 2
function module.getHiddenValue()
	return hiddenValue
end

return module
--(Local)Script

local MOD = require(game.ReplicatedStorage.ModuleScript)

print(MOD.sharedVar) --> 27
print(MOD.getHiddenValue()) --> 2
MOD.sharedVar = 16
print(MOD.hiddenValue) --Errors, since that isn't in the Table.


--A Different script, some time later...
local mud = require(game.ReplicatedStorage.ModuleScript)
print(mud.sharedVar) --> 16, since it was set to 16 in the previous Script.

There is a single caveat to this: Each individual client (including the Server running the game) gets its own copy of the module table.

Modifying it on any of the clients only affects that client, and no others.

2 comments

0

Thank you. That code works and also did what I could not figure out with the wiki about how modulescripts work (I still have more to learn though

0

Basically, MOD and mud in those two scripts is a direct pointer to the module Table created in the ModuleScript proper.

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