Module scripts function almost exactly the same as regular scripts, there’s just one small difference: It has to return something (and it can only do this once). You can return any valid value (even nil
is valid!), but, it has to return something, otherwise you will get an error.
You can also call modulescripts for “modules”, because that’s basically what they are, modules for your scripts. ReturnedTrue gave a very nice example on how they work!
Explanation on environment
A module works on both the server and the client, and the key point here is that they run in the “environment” they were required in. What this means, is that if you “require” a module on the client (from a LocalScript), the module will work as if it was a LocalScript. And as you probably know, a LocalScript cannot access certain things on the server (for example ServerScriptService and ServerStorage).
If you require a module from a Script on the server, the module will work as if it was a regular script on the server. This is what is meant by the environment it is required from.
Examples on how modules work
Let’s take an example! Presume the following code is in a LocalScript only:
local functions = {
hello = function ()
print("Hello, world!")
end;
};
functions.hello() --> "Hello, world!"
As you see, there is a table called functions
and it has a function called hello
. If you call functions.hello()
it will print out Hello, world!
Now, instead of having the table functions
in the LocalScript, you can instead put it in a module. This will allow for more modularization in your code!
Now, another example, just this time there will be a module and a localscript! Check it out:
The Module:
local functions = {
hello = function ()
print("Hello, world!")
end;
};
-- Remember you have to return something
return functions;
Image
and the LocalScript:
local functions = require(script.Parent.ModuleScript);
functions.hello() --> "Hello, world!"
Image