PcoWSkbVqDnWTu_dm2ix

5 min

Copying code to multiple scripts is time consuming and hard to manage. A better way to organize and reuse code is by using a ModuleScript, a unique type of script that returns a single value, usually a articles/Table|table or articles/Function|function that’s useful to multiple scripts.

CarScript (Script in ServerScriptService)
-- Get value returned by ModuleScript
local Car = require(script.Car)

-- Use a ModuleScript variable
print(Car.topSpeed)  --> 120

-- Call a ModuleScript function
Car.sound("Horn")  --> Horn
Car.sound("Alarm")  --> Alarm
Car.sound("Unlock")  --> Unlock
Car (ModuleScript within CarScript)
local Car = {}

Car.topSpeed = 120

function Car.sound(sound)
    print(sound)
end

-- This is returned by require()
return Car

Writing ModuleScripts

ModuleScript|ModuleScripts are commonly placed in ServerScriptService when used by server-side Script|Scripts and ReplicatedStorage when used by client-side LocalScript|LocalScripts. However, ModuleScript|ModuleScripts can be used when parented to any object, as long as another script has access to it.

When created, a ModuleScript starts out with this code:

The line local module = {} creates an empty table to store the module’s contents. This table is then returned (return module) so that it’s provided to other scripts which access the module.

You should rename this table (and modify the return line) according to the module’s purpose, such as PickupManager. It’s also a good idea to rename the ModuleScript itself to match.

Adding to ModuleScripts

To add a variable or function to the table returned by the module, use dot notation as illustrated below.

Variables

Functions

If certain variables or functions do not need to be exposed outside of the module, you can omit them from the returned table. Below, the defaultMultiplier variable and rarityMultipliers table are only used by the module’s getPickupBonus() function, so they don’t need to be added to the PickupManager table.


Accessing Modules From Other Scripts

A ModuleScript doesn’t run its code by itself — another script needs to access it using the built-in require() function. This accepts the ModuleScript as its only argument. For example, if a ModuleScript is located within ReplicatedStorage, you can access it from another script as follows:

Calling Module Functions

Once the module is loaded, you can call any of its functions with a similar dot notation format.

Tags:
  • lua
  • module
  • script