Why to use ModuleScripts.

Splitting up your code into modules may help a lot when debugging etc. So why don't you start using them today?

by SyntaxMenace

Author Avatar

Why Modules?

ModuleScripts allow you to split up parts of your code into more Instances to help you organize your code.

Here's an example:

Let's say we have a function that creates a 1x1 neon cube in workspace.

local function NewBlock(Position: Vector3, Color: Color3)
	local Part = Instance.new("Part");
	Part.Color = Color;
	Part.Size = Vector3.one;
	
	Part.Position = Position;
	Part.Parent = workspace;
	
	return Part;
end

Now let's say we have multiple different scripts that use this function

A Script using NewCube

local Button = workspace.Part;

local function NewCube(Position: Vector3, Color: Color3)
	local Part = Instance.new("Part");
	Part.Color = Color;
	Part.Size = Vector3.one;

	Part.Position = Position;
	Part.Parent = workspace;

	return Part;
end

Button.Touched:Connect(function()
	NewCube(Button.Position, Color3.new(1, 0, 0));
end)

But oh no! You've just realized you have forgotten to anchor the cube!

Now you have to go through the painful process of updating all the scripts that use the NewCube function one by one.


This is just one example where ModuleScripts come in very handy. You can just add that function in one module then access it through every script in your game!

New ModuleScript

local module = {};

function module.NewCube(Position: Vector3, Color: Color3)
	local Part = Instance.new("Part");
	Part.Color = Color;
	Part.Size = Vector3.one;
	
	Part.Anchored = true;
	Part.Position = Position;
	Part.Parent = workspace;

	return Part;
end

return module;

Updated Script

local ServerStorage = game:GetService("ServerStorage");
local NewCube = require(ServerStorage.ModuleScript).NewCube;
local Button = workspace.Part;

Button.Touched:Connect(function()
	NewCube(Button.Position, Color3.new(1, 0, 0));
end)

Splitting your code into modules helps with debugging, creating cleaner code, and reducing confusion overall!

View in-game to comment, award, and more!