ModuleScript

ModuleScript : LuaSourceContainer

Overview

A ModuleScript is a script instance used to separate common functionalities and structure them for reuse.

It can be loaded using the require() function, returning a single value upon when called. It means, even if multiple scripts in the same execution environment call require() on the same ModuleScript, the module executes only once, and subsequent calls share the initially returned value. By minimizing redundancy and defining functionality in a single location for shared use across different locations, it significantly enhances maintainability and reusability.

In distinct execution environments, such as server and client, a ModuleScript runs independently. For instance, a ModuleScript that has already been executed on the server will be executed again when calling require() on the client.

The require() function typically does not halt execution flow by default. However, if a ModuleScript employs a wait function, such as wait(), the calling thread pauses until the ModuleScript returns a value. As circular references, where ModuleScripts mutually require() each other, can cause threads to freeze, meticulous dependency management is critical in large-scale projects.

A ModuleScript can define properties and functions in a table and return it for external scripts to reference.

local UtilityModule = {}

UtilityModule.IsShowMessage = true

-- When a function is defined with colon, it can reference the table using self within the function.
function UtilityModule:PrintMessage(message)
    if not self.IsShowMessage then
        return
    end
    print("PrintMessage : " .. message)
end

return UtilityModule

External scripts can use the require() function to retrieve this table via ModuleScript, granting access to its defined properties and functions.

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UtilityModule = require(ReplicatedStorage:WaitForChild("UtilityModule"))

UtilityModule:PrintMessage("Hello!")

UtilityModule.IsShowMessage = false
UtilityModule:PrintMessage("Hello!")

Properties

Methods

Events

See also

Module Script

Last updated