What are Module Scripts what do they serve?

I heard a lot of people talking about global functions and saying to replace them by Module Scripts, I sort of understand what they are but what is the actual difference between them and using _G. ?

5 Likes

There are some great articles here about this subject. Here are a few:

https://devforum.roblox.com/t/when-should-i-use--g-instead-of-a-modulescript/13444

2 Likes

You can see which is better if you put it this way

Module Scripts can improve the functionality of _G, while _G can’t improve Module Scripts.

Module Scripts are basically scripts that you can access from external scripts for various functionalities like, creating a function for code that has over 100 lines that is used repeatedly, a local data container (different from data stores), bridges script connections and other stuff.

ModuleScript API-Reference says A ModuleScript is a type of Lua source container that runs once and must return exactly one value. This value is then returned by a call to require given the ModuleScript as the only argument. ModuleScripts run once and only once per Lua environment and return the exact same value for subsequent calls to require. but in my opinion Module Scripts are Scripts that do not run when the game starts and store some functions which can be useful later.

Let’s say you have a big Table or a Function. I would not store that Table/Function in the Script to keep the Script clean and easy to read.

Let’s create our first ModuleScript.

-- Module Script
local Prices = {

["Mango"] = 30,

["Banana"] = 15,

["EasterEgg"] = 9999

}

return Prices

To get that Table do:

-- Script
local FruitPrices = require(game.ServerScriptService.ModuleScript)

-- Then you simply print it.

print(FruitPrices["Mango"])
print(FruitPrices["Banana"])
print(FruitPrices["EasterEgg"])

The output will be:
30 15 9999

Now, let’s store a function.

-- Module Script
local Prices = {

["Mango"] = 30,

["Banana"] = 15,

["EasterEgg"] = 9999
}
--[[
To create a function you do:

modulename.functionname = function(argumentsifneeded)
function here
end
--]]

Prices.MyFunction = function(PriceToPrint)

print(PriceToPrint)

end

return Prices

Now to call that function:

-- Script
local FruitPrices = require(game.ServerScriptService.ModuleScript)

FruitPrices.MyFunction("Banana") -- Will print Banana
FruitPrices.MyFunction(FruitPrices["Banana"]) -- Will print Banana price (15)

I hope I helped you.

26 Likes