How To Use Module Scripts

Learn how to use Module Scripts and why ModuleScripts are useful in Roblox Scripting with this tutorial.

I’ve just launched my Roblox Advanced Scripting series on YouTube. With each episode, I will be writing a text version of my tutorial, as I know many people learn in different ways and reading can be a better method than video for some.

Module Scripts are really useful in Roblox Scripting. They help us to stop writing the same code over and over again in different scripts, because we can write the code only once in a ModuleScript and then call it from multiple different scripts.They’re also useful for handling information, such as information for all pets in your game that are available to buy.

Basics

Think of Module Scripts as containers. You write functions in your module scripts, and then you call them from other scripts. When you call these functions, they’re actually being executed in the same environment as the script you call them from. So if you have a ModuleScript in ReplicatedStorage, and you call a function inside of it from a local script, it will be running that function on the client, as if the code was in that localscript. If you were to call a function in there from a Server script, the code would run on the server. What I’m trying to say is, when you call a function inside a module script, it’s not running in the module, it’s running in the script environment you called it from.

How do I write code in a ModuleScript?

Very easy. We write code in functions which go inside the module table. To create a function:

local module = {} -- Create module table, to contain all the data we want to return.
function module.Print(text) -- Create a function called Print, insert it inside module table (hence, module.Print)
    print(text)
end
return module -- Return the module table, which contains all the functions, back to wherever it gets required.

And yes, you can change the name of the module variable, that’s the default but it doesn’t matter what
you call it. End of the day all that matters is that you return some data.

How do you get the functions / code out of the ModuleScript?

Good question. You may wonder how you can access these functions which are stored inside the Module from other scripts. There’s a nifty function called require() which we can use for this.

A module script has to return something. When you first create a module script, you’ll see that it gives you a variable called module, which is a table. That gets returned.

When you use the require function, you pass the reference to your module. You also set the require function to a variable:

local myModule = require(game.Workspace.MyModule)

What happens is, the require function will get the data which is returned from the module script. So that table called module, gets returned to the myModule variable. And because any functions we create in the module script are inside the module table, they are inside the returned table. So we can now execute these functions!

Remember, the returned data is actually a “copy” of the actual data inside the module, which is why when you execute the functions the code isn’t running in the module script, it’s running in the script environment which we required the modulescript from because the require statement “downloaded” a copy of the returned data from the modulescript.

But wait, there’s more!

ModuleScripts aren’t just used for functions. I mentioned earlier, that they’re useful for containing information about things in your game. For example, they can be used for databases. Let me show you an example.

Your game sells different pets, all of which have their own values for their age, max health, cost, etc. We want to store this data somewhere so it can be accessed from different scripts:

Client GUI scripts will want to access the database to show all available pets for sale and to get the information about each pet to show its unique traits / values

Server scripts will want to access the database to get the price values of each pet to make sure, when checking a transaction, whether the buyer has enough money to afford the pet

When a player joins, their DataStore only tells the name of the pet, to save character space in Data Store. The database can be used to lookup the information of that pet, including the object path to it, so it can easily be found and cloned for that player

ModuleScripts can return anything, really. So instead of a table, you could return a string, or a number. I’ve never really used ModuleScripts for returning anything other than tables, either with or without functions. But if you wanted to have a database in your module for all your pets, you’d need a big table containing sub tables for each pet, which will contain the values such as age, health, etc. This is called a Dictionary.

A dictionary is a big table with sub tables, which have keys and values. The value is the sub table, and the key is the name of each sub table.

local database = { -- Main dictionary table.

	["Dragon"] = { -- A sub table inside this dictionary. Dragon is the key (name) which makes looking up a specific pet easier.
		["Health"] = 500; -- Sub key / value pairs inside this table, so you can easily lookup the value you want using the key.
		["Age"] = 5;
		["Price"] = 50;
	}; -- Semi colon or comma needed to seperate from the next value!
	
	["Cat"] = {
		["Age"] = 9, -- Notice how I'm using commas here, instead of semi colon? They do the same thing :)
		["Price"] = 20, -- Make sure you seperate each sub value inside the table with a semi colon/comma as well!
		["Health"] = 50,
	}
}

return database -- This database table will get returned to any script which requires the module.

Script requiring the module (local or server, doesn’t matter as it’s in ReplicatedStorage)

-- Once required, the script will be able to have information about every pet in the game.

local petDatabase = require(game.ReplicatedStorage.PetModule)

print(petDatabase["Cat"]["Age"]) -- Will print 9. 

In the script above, it looks up the Age value of the Cat inside the database table, which was returned to the script. The table is a copy of the one from the ModuleScript, now stored in the script which required it.

Hope that tutorial was useful! My first one, so hopefully they’ll get better with time. Don’t forget to watch the video at the top to cement your understanding, and subscribe / like if you’d like more! With all this free time I’ll be making many more, some of which already are on my website. Do let me know if I missed anything or made a mistake.

181 Likes

Hey, this was some awesome stuff.

I am already subscribed to you, my friends and I used your sword ffa tutorial

7 Likes

Finally! have been waiting for the advanced series :slight_smile:

8 Likes

I’m here too. Nice tutorial :ok_hand: :grin:

4 Likes

Glad to see the advanced scripting tutorial out! Also, glad to see you writing tutorials! This will help me and all the people who learn by reading!

Next video on OOP pwease

9 Likes

Interesting new style of using a video in addition to a dev forum write up. You continue to be my go-to recommendation for anyone who comes to me trying to learn Lua :+1:

6 Likes

If I use the module in different scripts at once, will it cause something like overload?

2 Likes

@Alvin_Blox What happens when you don’t put a colon in the database part? ×

It’s a semi-colon, not a colon.
Anyways, in that place, you can use either a semi-colon, or a comma. If you miss that, an error will be thrown. It’s pretty much a token to distinguish between different data entries. Pretty much like the array:

["Dragon", "Cat", "Ferret", "Dog"]

It’s pretty similar to JSON.

Correct me if I’m wrong about the token thing

4 Likes

Awesome tutorial! Keep up the good work, I am always inspired by you ever since I started watching your channel. Can’t wait to see what comes next, this is the area I need to learn in (probably more near the end of the series, but still love the useful tutorials). :smiley:

I am a old fan ever since you had 50K subscribers, I am pretty sure there may be even older fans but just something to let you know.

6 Likes

I had no idea how to use Module scripts… Until now. Keep up the good work!

Can you do a pathfinding tutorial

3 Likes

I wish this had been posted a while ago, I had to go to what felt like 100 places to figure out modulescripts.

3 Likes

YES THANK YOU. No one really knows about ModuleScripts except for some people. AlvinBlox back at it again!

4 Likes

I use commas, semicolons feel weird.
It will return an error.

2 Likes

Nope you can require and call from different scripts at once! As the contents of the module are ‘copied’ when you require it it’s running in that script’s environment so it won’t overload the module.

7 Likes

Really helpful and allowed me to learn the basics of module scripts easily :+1:

Really helped, mainly database part. Thanks Alvin.

thx for the tutorial Alvin_Blox

2 Likes

amazing tutorial, thank you very much :slight_smile: