Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

Module script usage?

Asked by 10 years ago

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

1 answer

Log in to vote
2
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
10 years ago
01--ModuleScript (in ReplicatedStorage if you want to use LocalScripts to require it, ServerScriptService otherwise)
02 
03local module = {}
04module.sharedVar = 27 --Anything inside this table is accessible to things that require() this module.
05hiddenValue = 2
06function module.getHiddenValue()
07    return hiddenValue
08end
09 
10return module
01--(Local)Script
02 
03local MOD = require(game.ReplicatedStorage.ModuleScript)
04 
05print(MOD.sharedVar) --> 27
06print(MOD.getHiddenValue()) --> 2
07MOD.sharedVar = 16
08print(MOD.hiddenValue) --Errors, since that isn't in the Table.
09 
10 
11--A Different script, some time later...
12local mud = require(game.ReplicatedStorage.ModuleScript)
13print(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.

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 MrLonely1221 701 — 10y
0
Basically, `MOD` and `mud` in those two scripts is a direct pointer to the `module` Table created in the ModuleScript proper. adark 5487 — 10y
Ad

Answer this question