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

Whats a module script, whats different from normal scripts?

Asked by 6 years ago

Ive seen this thing for awhile and i never really understood what it does.

1 answer

Log in to vote
1
Answered by
metryy 306 Moderation Voter
6 years ago
Edited 6 years ago

Module scripts are mainly used to store functions that are used in multiple scripts in games. Unlike regular scripts, module scripts only return one value that's returned when you require the modulescript.

One example: people use module scripts to store their datastore functions so they can use them in multiple scripts without having to rewrite the function in each script. Example:

local DataStore = {}

local PlrData = {
    level = 1, 
    xp = 0
}

function DataStore:AddPlayer(Plr)
    local MyData = Data:GetAsync(Plr.UserId) or {}
    MyData.Ah = MyData.Ah or "Yes"

    PlrData[Plr.UserId] = MyData
end

function DataStore:RemovePlayer(Plr)
    if PlrData[Plr.UserId] then
        Data:SetAsync(Plr.UserId, PlrData[Plr.UserId])
        PlrData[Plr.UserId] = nil
    end
end

return DataStore

So then, you can require the module script from another script and use the functions as normal:

local DataStore = require(modulescript) -- require the module script 

for I, V in next, Players:GetPlayers() do
   DataStore:AddPlayer(V)
end

Players.PlayerAdded:Connect(DataStore:AddPlayer)

if not game:GetService("RunService"):IsStudio() then
    Players.PlayerRemoving:Connect(DataStore:RemovePlayer)
end

Hope this helped. If you have any questions comment below :)

0
thanks really helped Metraria 17 — 6y
0
Just to add to this, modules are a collection of functions which can be used later without having to type them again. The lua libraries (math, os etc) are all modules. turtle2004 167 — 6y
Ad

Answer this question