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!