How do I do modular scripting?

I’m making a game for an independent study course at my school. So far I’ve built the maps and everything looks good so far, however, I don’t know that much about scripting. I’ve been writing everything within a global script (of course I know some functions can only be done through a local script), although I’m not very far in (only a few hundred lines). Only now am I reading up on what the least impactful and cleanest scripting is and most people are saying that “modular scripting” is better than just doing it in one script.
I have looked through a lot of articles here on the Devforum, but I can’t find any that actually describe how to do this in general. What’s the best way to go about modular scripting? How do I use ModuleScripts? If it’s too much to explain, can anyone link me to some useful webpages or articles that explain how to do it?

I’ve copied a function into a ModuleScript if you want to review it. I don’t know exactly how to do it but looking at code allows me to figure it out normally.

local timerGui = {}

while true do
	wait()
	
	-- Search for mainMap
	repeat
		print("Finding mainMap")
		wait(.25)
	until workspace:FindFirstChild("mainMap") ~= nil
	
		
		-- Define the function
		function waitToTeleport()
			local timerNumber = game.StarterGui.Timer.Number.Text
			for i = 30,0,-1 do
				timerNumber = tostring(i)
				wait(1)
			end
		end
		-- Call the function
		waitToTeleport()
		
	end
	
end

return timerGui

I have not tested it in any way, nor do I know how to write a script like this. If you want to point out some errors, I would love to know what I’m doing wrong, if anything.

Pictures of your organization methods are incredibly helpful as well.

Thank you!

1 Like

The purpose of modules is to simplify sharing common data or functions between scripts, organizing and structuring your code.
The module will only be ran once on first require and the returned value will be cached permanently from that point. In most cases you’d want the return value to be a table since you can easily modify its contents.

For example, code which will be used both on the client and the server can be put into a module script inside ReplicatedStorage; Player data which needs to be accessible from different scripts can be handled inside a module, a lot of functions sharing one purpose like math can make a module, etc.

The code you sent above is very much something you wouldn’t want to do in a ModuleScript: It never returns, causing the require(path.To.Your.Module) statement to be a script terminator. If you’d like to run an infinite function or loop simultaneously to the rest of the script, use spawn or coroutines.

There’s a nice introduction to modules with examples here:

5 Likes