top of page

Understanding Module Scripts

Updated: Aug 27, 2023






What is a Module Script

A module script is a type of source container. It is an essential part of coding when you want to stick to the DRY (Don’t repeat yourself) principle. Place the functions you want to use in the module script and access the same functions from different scripts. Module scripts can also perform other coding functions such as acting as a dictionary, or holding class information. Let’s look at some examples below.


Where can you use a Module Script?

Module scripts can be used on the server or the client. It is important to realise however that if a module script is run on a client then it is independent from the server, and if it is on the server it is independent of the client. In most cases when you create a module script it is to serve a purpose in your project. For example you may create an animations module script to run on the client to handle all the player animations, and on the server you may create one to just run functions.


How to use a Module Script

There are a couple of important things to remember when using a module script.

  1. Module scripts do not run any code contained within them until they are required by another script.

  2. Any code in the module script that is not inside a function will run when it is required by another script.

  3. Two module scripts should never require each other as this will cause a cyclical redundancy error. Similar to a while loop with no wait() and may crash the program or your computer!

To create a module script click on the + next to the ServerScriptService folder. Click on ModuleScript.


To create a function in a module script you should follow the following steps.


Type the keyword function - then a space and the name of the module - Add a full-stop then type the name of your function followed by parentheses and hit enter.


function module.SayHello()
	- - function code goes in here.  
end

To require and use the function create a script in ServerScriptService, and add the following at the top.

local myMod = require(game.ServerScriptService.ModuleScript)

To run the function in the module script. Type the following

myMod.SayHello()

The message in the function should print to the output window in Roblox Studio.


Functions in module scripts that return values can be assigned to variables, and perform in the same way as you would expect if it were a local function.


For more information about module scripts click on the link at the top to read about them in the Roblox API.


To learn to use them in creative ways, get the best purchase price for my courses by clicking on the webpage links. They are available on Udemy, and Skillshare.

84 views0 comments

Recent Posts

See All

Comentarios

Obtuvo 0 de 5 estrellas.
Aún no hay calificaciones

Agrega una calificación
bottom of page