From the wiki:
" Its code is executed at the point it is required, and will only be executed once per peer (server/client). If a ModuleScript is required multiple times in the same environment the return value from the first execution will be used for every require call."
I've been using ModuleScripts for a while now and have never come across this causing an error but I'm not exactly sure what it means.
In my latest project I am going to be passing several values to a ModuleScript function which will then iterate over some tables and return a value. Will I encounter problems with multiple users calling these functions with different values? What do those lines from the wiki mean?
Thanks, MD
This is not a limitation -- it's actually a very nice feature.
It means that if two different scripts require
the same module, they get the same object.
That means if you had the following modulescript:
----- ModuleScript workspace.Counter local n = 0 function count() n = n + 1 return n end return count
If two different scripts require
that module:
----- Script A A = require(workspace.Counter) print( A() ) print( A() ) print( A() )
----- Script B B = require(workspace.Counter) print( B() ) print( B() ) print( B() )
The counter is not separate for each script -- the second one will continue counting 4
5
6
, not have its own "fresh" copy that restarts at 1
.
If you don't want to share, it's really easy to change how that works. Just make sure you, instead of returning the thing you don't want shared, return a function which makes a new thing. Then the scripts would look like
function MakeCounter() local count = 0 return function() count = count + 1 return count end end return MakeCounter
MakeCounter = require(workspace.MakeCounter) local A = MakeCounter() print(A()) -- 1 print(A()) -- 2 print(A()) -- 3
MakeCounter = require(workspace.MakeCounter) local B = MakeCounter() print(B()) -- 1 print(B()) -- 2 print(B()) -- 3
Remark: If your modulescripts are pure -- without side-effects -- they don't change anything about themselves (calling functions in any order doesn't affect what answers you get) then whether or not they return something fresh for each script doesn't change how it works at all.
(In general pure functions are nicer to think about, because of things like this, but not always practical)