Module Script Questions

I have a few questions about these type of scripts

What are there use cases?
What are they in general?
How do you setup one?
Do they get replicated to the client?

These are all answered in a YouTube tutorial video. Please consider searching for answers before making these topics.

4 Likes

summed up, module scripts are script in wich you can store functions for other scripts to execute.
Module scripts can be used by both the server and the client.
A module script can be used by making a function in the modulescript and making that function part of the value module() like this:
function module.existance is pain () print(“Existance is pain”)
end
The functions within the module can be accessed by using require(module) in other scripts.
The most common use cases for module scripts are for when a script gets too big and complicated.
Noone wants to look through 1k lines of code to find that one line that needs a bugfix.
Splitting it up into modules can splify bugfixing and programming.

1 Like

Please read this article, to know more.

TL;DR:

  1. Their use cases come in two main areas.
    a. For organising code.
    b. For creating classes (which is again another form of code organisation but more specific)

  2. They are a type of script that doesn’t run independently. They need to be require(ModuleScript) from an external LocalScript or Script to be executed.

  3. To set up a ModuleScript you need to organise your ModuleScript code such that it returns one item. In most cases, we return a table of values, as shown here.

local Module = {}

function Module.new(x)
    local self = setmetatable({}, {__index=Module})
    self.x = x
end

return Module
  1. They are replicated to the client in the same way that other Instances are. This means that ModuleScripts in ReplicatedStorage, for example, replicate to the client but ModuleScripts in ServerStorage will not.

n.b. When requiring a ModuleScript from the client, it will run locally, and when requiring one from the Server via a Script, it will run on the server. In other words, the ModuleScript will execute on it’s callers’ environment.

n.b Again that when you run a ModuleScript the main body will execute only once. E.g.

--<< IN A MODULE >>

local Module = {}

print("Hello")

return Module

-- << IN A SCRIPT >>

require(Module)
require(Module)

-- << OUTPUT >>

>> Hello

Think of it as an initialisation, which is then never repeated.

4 Likes

Thanks for the answer, hopefully now I can finish off what my system needs

1 Like

Modules can also store dictionaries. You can think of them as remote tables / object tables.

1 Like