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
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
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!
This discussion is preserved as it was. New answers, comments, and votes are closed.
3 comments
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?
Yes, it is also good for storing data tables, and questions like: m.Questions = {
Ah sorry, like: M.Question = { Question1 = "Hello, are you cool", Question2 = "Okay, do you like Pizza?"}