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
--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.

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