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

How does module scripts work? Why do we use them? Why is it useful?

Asked by 4 years ago

I want to know about module scripts. Why do we use Module scripts? Why is it useful? I want to know why. If you answer this, I would be very happy!

Sincerely,

Ducksneedhelp

1 answer

Log in to vote
0
Answered by
notfenv 171
4 years ago

Module Scripts are basically like a normal script but it can be used in many ways. First, with requiring it in a script, do require() then where it's found. Example: require(script.Parent.Module)

You can do a lot with modules, for storing functions, etc. If you want to use functions and you don't want to put it inside your main code, you can create a module for it! Let's say:

function PrintThingy(Message)
    print(Message)
end

Now, for your main code.

game.Players.PlayerAdded:Connect(function(Player)
    if Player ~= nil then
        PrintThingy(Player.Name .. " has joined the game!")
    end
end)

Now, if you want to do this in a module script, you'll simply get some automated code like this:

local module = {}

return module

Do keep this, as it is essential, although you can rename it.

Now, paste your function inside the 2 pieces of code, and do:

function M:PrintThingy(Message)
    print(Message)
end

It should now look like:

local module = {}

function M:PrintThingy(Message)
    print(Message)
end

return module

Now to use it. Define the module with the require function inside your main code.

local Module = require(script.Parent.ModuleScript)

And now, to call the function.

game.Players.PlayerAdded:Connect(function(Player)
    if Player ~= nil then
        Module:PrintThingy(Player.Name .. " has joined the game!")
    end
end)

This makes it much easier to make datatables and such as well, instead of storing it in one script.

Let's say a store table right? Maybe:

local M = {}

M.ShopData = {
    ["Sword"] = {
        Price = 333,
        Description = "A sharp sword!"
    }
}

return M

Then you can require it, and use a for loop to get the shopdata. Hope this helps!

0
As I got the point with was, it is a better way to store code instead to do it in a main script. Is that right? Ducksneedhelp 129 — 4y
0
Yes, it is also good for storing data tables, and questions like: m.Questions = { notfenv 171 — 4y
0
Ah sorry, like: M.Question = { Question1 = "Hello, are you cool", Question2 = "Okay, do you like Pizza?"} notfenv 171 — 4y
Ad

Answer this question