API:Class/ModuleScript

< API:Class(Redirected from ModuleScript)

ExplorerImageIndex76.pngModuleScript : Object Icon.pngLuaSourceContainer : Object Icon.pngInstance

A ModuleScript is a Script-like object that contains code for a module. Unlike other scripts, a module does not execute when a game starts. The code in a module script can be run by calling the require global function with the ModuleScript as an argument. Its code is executed at the point it is required, and will only be executed once per peer (server/client). If a ModuleScript is required multiple times in the same environment the return value from the first execution will be used for every require call.


When writing code for a large project, you may find yourself defining the same function in several different places. Using module scripts, you can define a function in one place to be used in any number of scripts. This makes maintaining and updating code much easier, as you only have to make changes in one place (as opposed to searching for all the scripts where you use the function).

Properties

PropertiesmemberhiddenProperties [toggle]

ContentLinkedSource

Used to store a URL that points to an online script source. Binds the online code to the script's Source.

|RMD member="API:Class/ModuleScript/LinkedSource"|Used to store a URL that points to an online script source. Binds the online code to the script's Source.|/RMD|
ProtectedStringSource [PluginSecurity]

The code to be executed.

|RMD member="API:Class/ModuleScript/Source"|The code to be executed.|/RMD|
Used to store a URL that points to an online script source. Binds the online code to the script's Source.
Source [PluginSecurity]
The code to be executed.
Inherited from Object Icon.pngLuaSourceContainer:
Ref<Player>CurrentEditor [NotAccessibleSecurity]

The Player who is currently editing this script. This property is only used when in Team Create mode.

|RMD member="API:Class/LuaSourceContainer/CurrentEditor"|The Player who is currently editing this script. This property is only used when in Team Create mode.|/RMD|
CurrentEditor [NotAccessibleSecurity]
The Player who is currently editing this script. This property is only used when in Team Create mode.
Inherited from Object Icon.pngInstance:
boolArchivable

Determines if an object can be Clone or saved to file.

|RMD member="API:Class/Instance/Archivable"|Determines if an object can be Clone or saved to file.|/RMD|
stringClassName [readonly]

The unique name of this type of Instance.

|RMD member="API:Class/Instance/ClassName"|The unique name of this type of Instance.|/RMD|
stringName

A non-unique identifier for the object.

|RMD member="API:Class/Instance/Name"|A non-unique identifier for the object.|/RMD|
Ref<Instance>Parent

The hierarchical parent of the object.

|RMD member="API:Class/Instance/Parent"|The hierarchical parent of the object.|/RMD|
intDataCost [LocalUserSecurity] [deprecated] [readonly]

Deprecated. Do not use.

|RMD member="API:Class/Instance/DataCost"|Deprecated. Do not use.|/RMD|
boolRobloxLocked [PluginSecurity]

If true, the object and its descendants cannot be indexed or edited by a Script or LocalScript and will throw an error if it is attempted.

|RMD member="API:Class/Instance/RobloxLocked"|If true, the object and its descendants cannot be indexed or edited by a Script or LocalScript and will throw an error if it is attempted.|/RMD|
boolarchivable [deprecated] [hidden]

Deprecated in favor of Archivable.

|RMD member="API:Class/Instance/archivable"|Deprecated in favor of Archivable.|/RMD|
stringclassName [deprecated] [readonly]

Deprecated in favor of ClassName.

|RMD member="API:Class/Instance/className"|Deprecated in favor of ClassName.|/RMD|
Determines if an object can be Clone or saved to file.
ClassName [readonly]
The unique name of this type of Instance.
A non-unique identifier for the object.
The hierarchical parent of the object.
DataCost [LocalUserSecurity] [deprecated] [readonly]
Deprecated. Do not use.
RobloxLocked [PluginSecurity]
If true, the object and its descendants cannot be indexed or edited by a Script or LocalScript and will throw an error if it is attempted.
archivable [deprecated] [hidden]
Deprecated in favor of Archivable.
className [deprecated] [readonly]
Deprecated in favor of ClassName.

Functions

FunctionsmemberhiddenFunctions [toggle]

Inherited from Object Icon.pngInstance:
voidClearAllChildren ( )

Removes all descendants of the object.

|RMD member="API:Class/Instance/ClearAllChildren"|Removes all descendants of the object.|/RMD|
Ref<Instance>Clone ( )

Returns a copy of the object, including descendants, but only if the object is Archivable.

|RMD member="API:Class/Instance/Clone"|Returns a copy of the object, including descendants, but only if the object is Archivable.|/RMD|
voidDestroy ( )

Sets the Parent property to nil, locks the Parent property, disconnects all connections and calls Destroy() on all children.

|RMD member="API:Class/Instance/Destroy"|Sets the Parent property to nil, locks the Parent property, disconnects all connections and calls Destroy() on all children.|/RMD|
Ref<Instance>FindFirstAncestor ( string name )

Returns the first ancestor whose Name is equal to name, or nil if none can be found.

|RMD member="API:Class/Instance/FindFirstAncestor"|Returns the first ancestor whose Name is equal to name, or nil if none can be found.|/RMD|
Ref<Instance>FindFirstAncestorOfClass ( string className )

Returns the first ancestor whose ClassName is equal to className, or nil if none can be found.

|RMD member="API:Class/Instance/FindFirstAncestorOfClass"|Returns the first ancestor whose ClassName is equal to className, or nil if none can be found.|/RMD|
Ref<Instance>FindFirstAncestorWhichIsA ( string className )

Returns the first ancestor that inherits the class className, or nil if none can be found.

|RMD member="API:Class/Instance/FindFirstAncestorWhichIsA"|Returns the first ancestor that inherits the class className, or nil if none can be found.|/RMD|
Ref<Instance>FindFirstChild ( string name, bool recursive = false )

Returns the first child found with the given name, or nil if no such child exists. If the optional recursive argument is true, recursively descends the hierarchy while searching rather than only searching the immediate object.

|RMD member="API:Class/Instance/FindFirstChild"|Returns the first child found with the given name, or nil if no such child exists. If the optional recursive argument is true, recursively descends the hierarchy while searching rather than only searching the immediate object.|/RMD|
Ref<Instance>FindFirstChildOfClass ( string className )

Returns the first Instance whose ClassName is equal to className, or nil, if no such object is found with that ClassName.

|RMD member="API:Class/Instance/FindFirstChildOfClass"|Returns the first Instance whose ClassName is equal to className, or nil, if no such object is found with that ClassName.|/RMD|
Ref<Instance>FindFirstChildWhichIsA ( string className, bool recursive = false )

Returns the first child that inherits the class className, or nil if none can be found.

|RMD member="API:Class/Instance/FindFirstChildWhichIsA"|Returns the first child that inherits the class className, or nil if none can be found.|/RMD|
array<Instance>GetChildren ( )

Returns an array of the object's children.

|RMD member="API:Class/Instance/GetChildren"|Returns an array of the object's children.|/RMD|
array<Instance>GetDescendants ( )

Returns an array containing all of the descendants of the instance.

|RMD member="API:Class/Instance/GetDescendants"|Returns an array containing all of the descendants of the instance.|/RMD|
stringGetFullName ( )

Returns a string which shows the object's ancestry chain.

|RMD member="API:Class/Instance/GetFullName"|Returns a string which shows the object's ancestry chain.|/RMD|
RBXScriptSignalGetPropertyChangedSignal ( string property )

Returns a signal that is fired when the specified property is changed on this object.

|RMD member="API:Class/Instance/GetPropertyChangedSignal"|Returns a signal that is fired when the specified property is changed on this object.|/RMD|
boolIsA ( string className )

Returns true if the object is an instance of the given class, or if the object's class inherits from the given class.

|RMD member="API:Class/Instance/IsA"|Returns true if the object is an instance of the given class, or if the object's class inherits from the given class.|/RMD|
boolIsAncestorOf ( Instance descendant )

Returns true if the object is an ancestor of the given descendant.

|RMD member="API:Class/Instance/IsAncestorOf"|Returns true if the object is an ancestor of the given descendant.|/RMD|
boolIsDescendantOf ( Instance ancestor )

Returns true if the object is a descendant of the given ancestor.

|RMD member="API:Class/Instance/IsDescendantOf"|Returns true if the object is a descendant of the given ancestor.|/RMD|
Ref<Instance>WaitForChild ( string childName, double timeOut )

Yields the current thread until a child with the given name is found, then returns the child. If the timeOut parameter is specified, this function will time out and return nil if timeOut seconds elapse without the child being found.

|RMD member="API:Class/Instance/WaitForChild"|Yields the current thread until a child with the given name is found, then returns the child.

If the timeOut parameter is specified, this function will time out and return nil if timeOut seconds elapse without the child being found.|/RMD|

stringGetDebugId ( int scopeLength = 4 ) [PluginSecurity] [notbrowsable]

Returns a coded string of the object's DebugId used internally by Roblox.

|RMD member="API:Class/Instance/GetDebugId"|Returns a coded string of the object's DebugId used internally by Roblox.|/RMD|
voidRemove ( ) [deprecated]

Deprecated. Do not use.

|RMD member="API:Class/Instance/Remove"|Deprecated. Do not use.|/RMD|
array<Instance>children ( ) [deprecated]

Deprecated in favor of GetChildren.

|RMD member="API:Class/Instance/children"|Deprecated in favor of GetChildren.|/RMD|
Instanceclone ( ) [deprecated]

Deprecated in favor of Clone.

|RMD member="API:Class/Instance/clone"|Deprecated in favor of Clone.|/RMD|
voiddestroy ( ) [deprecated]

Deprecated in favor of Destroy.

|RMD member="API:Class/Instance/destroy"|Deprecated in favor of Destroy.|/RMD|
InstancefindFirstChild ( string name, bool recursive = false ) [deprecated]

Deprecated in favor of FindFirstChild.

|RMD member="API:Class/Instance/findFirstChild"|Deprecated in favor of FindFirstChild.|/RMD|
array<Instance>getChildren ( ) [deprecated]

Deprecated in favor of GetChildren.

|RMD member="API:Class/Instance/getChildren"|Deprecated in favor of GetChildren.|/RMD|
boolisA ( string className ) [deprecated]

Deprecated in favor of IsA.

|RMD member="API:Class/Instance/isA"|Deprecated in favor of IsA.|/RMD|
boolisDescendantOf ( Instance ancestor ) [deprecated]

Deprecated in favor of IsDescendantOf.

|RMD member="API:Class/Instance/isDescendantOf"|Deprecated in favor of IsDescendantOf.|/RMD|
voidremove ( ) [deprecated]

Deprecated in favor of Remove.

|RMD member="API:Class/Instance/remove"|Deprecated in favor of Remove.|/RMD|
Removes all descendants of the object.
Clone ( )
Returns a copy of the object, including descendants, but only if the object is Archivable.
Sets the Parent property to nil, locks the Parent property, disconnects all connections and calls Destroy() on all children.
Returns the first ancestor whose Name is equal to name, or nil if none can be found.
Returns the first ancestor whose ClassName is equal to className, or nil if none can be found.
Returns the first ancestor that inherits the class className, or nil if none can be found.
FindFirstChild ( string name, bool recursive = false )
Returns the first child found with the given name, or nil if no such child exists. If the optional recursive argument is true, recursively descends the hierarchy while searching rather than only searching the immediate object.
Returns the first Instance whose ClassName is equal to className, or nil, if no such object is found with that ClassName.
FindFirstChildWhichIsA ( string className, bool recursive = false )
Returns the first child that inherits the class className, or nil if none can be found.
Returns an array of the object's children.
Returns an array containing all of the descendants of the instance.
Returns a string which shows the object's ancestry chain.
Returns a signal that is fired when the specified property is changed on this object.
IsA ( string className )
Returns true if the object is an instance of the given class, or if the object's class inherits from the given class.
IsAncestorOf ( Instance descendant )
Returns true if the object is an ancestor of the given descendant.
Returns true if the object is a descendant of the given ancestor.
WaitForChild ( string childName, double timeOut )
Yields the current thread until a child with the given name is found, then returns the child. If the timeOut parameter is specified, this function will time out and return nil if timeOut seconds elapse without the child being found.
GetDebugId ( int scopeLength = 4 ) [PluginSecurity] [notbrowsable]
Returns a coded string of the object's DebugId used internally by Roblox.
Remove ( ) [deprecated]
Deprecated. Do not use.
children ( ) [deprecated]
Deprecated in favor of GetChildren.
clone ( ) [deprecated]
Deprecated in favor of Clone.
destroy ( ) [deprecated]
Deprecated in favor of Destroy.
findFirstChild ( string name, bool recursive = false ) [deprecated]
Deprecated in favor of FindFirstChild.
getChildren ( ) [deprecated]
Deprecated in favor of GetChildren.
isA ( string className ) [deprecated]
Deprecated in favor of IsA.
isDescendantOf ( Instance ancestor ) [deprecated]
Deprecated in favor of IsDescendantOf.
remove ( ) [deprecated]
Deprecated in favor of Remove.


Events

EventsmemberhiddenEvents [toggle]

Inherited from Object Icon.pngInstance:
AncestryChanged ( Instance child, Instance parent )

Fires when the Parent property of the object or one of its ancestors is changed.

|RMD member="API:Class/Instance/AncestryChanged"|Fires when the Parent property of the object or one of its ancestors is changed.|/RMD|
Changed ( string property )

Fires after a property of the object changes.

|RMD member="API:Class/Instance/Changed"|Fires after a property of the object changes.|/RMD|
ChildAdded ( Instance child )

Fires when a child is added to the object.

|RMD member="API:Class/Instance/ChildAdded"|Fires when a child is added to the object.|/RMD|
ChildRemoved ( Instance child )

Fires when a child is removed from the object.

|RMD member="API:Class/Instance/ChildRemoved"|Fires when a child is removed from the object.|/RMD|
DescendantAdded ( Instance descendant )

Fires when a descendant is added to the object.

|RMD member="API:Class/Instance/DescendantAdded"|Fires when a descendant is added to the object.|/RMD|
DescendantRemoving ( Instance descendant )

Fires before a descendant of the object is removed.

|RMD member="API:Class/Instance/DescendantRemoving"|Fires before a descendant of the object is removed.|/RMD|
childAdded ( Instance child ) [deprecated]

Deprecated in favor of ChildAdded.

|RMD member="API:Class/Instance/childAdded"|Deprecated in favor of ChildAdded.|/RMD|
Fires when the Parent property of the object or one of its ancestors is changed.
Changed ( string property )
Fires after a property of the object changes.
Fires when a child is added to the object.
Fires when a child is removed from the object.
DescendantAdded ( Instance descendant )
Fires when a descendant is added to the object.
Fires before a descendant of the object is removed.
childAdded ( Instance child ) [deprecated]
Deprecated in favor of ChildAdded.

|RMD member="API:Class/ModuleScript"|A ModuleScript is a Script-like object that contains code for a module. Unlike other scripts, a module does not execute when a game starts. The code in a module script can be run by calling the require global function with the ModuleScript as an argument. Its code is executed at the point it is required, and will only be executed once per peer (server/client). If a ModuleScript is required multiple times in the same environment the return value from the first execution will be used for every require call. When writing code for a large project, you may find yourself defining the same function in several different places. Using module scripts, you can define a function in one place to be used in any number of scripts. This makes maintaining and updating code much easier, as you only have to make changes in one place (as opposed to searching for all the scripts where you use the function). |/RMD|


Notes

  • If the ModuleScript instance is renamed to 'MainModule' and uploaded to ROBLOX, scripts can use require on the AssetId of the uploaded ModuleScript, allowing the creation of private modules.
  • Module scripts are allowed to yield (e.g. if they call a yielding function, like wait()). When they do, any script currently require()ing it will also yield. ROBLOX guarantees that if the module script does not yield then require() will not yield.
  • A ModuleScript has to return exactly one value, but this can be anything: A function, a table, ... even just nil ('return nil' works, just 'return' will error)
  • This system is distinct from official roblox libraries.

Example

The typical use of a module is to return a table containing multiple functions, matching how the built in string, table, and math libraries work:

  • Tree-collapse.png
    Workspace
    Workspace
    • Tree-collapse.png
      ModuleScript
      MyModuleScript
        local _M = {}  -- name is only a convention, to mirror _G
         
        function _M.foo()
        	print("foo")
        end
         
        function _M.bar()
        	print("bar")
        end
         
        return _M
    • Part
      Button
    • Tree-collapse.png
      Script
      MyScript
        local myModule = require(game.Workspace.MyModuleScript)
        myModule.foo() -- prints "foo" to output
        myModule.bar() -- prints "bar" to output

Single-function modules

Sometimes, all you need a module to do is one function. This is even easier:

  • Tree-collapse.png
    Workspace
    Workspace
    • Tree-collapse.png
      ModuleScript
      MyModuleScript
        function printThis(value)
        	print(value)
        end
         
        return printThis
    • Tree-collapse.png
      Script
      MyScript
        local printModule = require(game.Workspace.MyModuleScript)
        printModule("Test Print") -- prints "Test Print" to output

Debounce

Here is a real-world example of a generic debounce function, which can be defined in a module script, then used in other scripts

  • Tree-collapse.png
    Workspace
    Workspace
    • Tree-collapse.png
      ModuleScript
      DebounceModule
        function debounce(func)
            local isRunning = false    -- Create a local debounce variable
            return function(...)       -- Return a new function
                if not isRunning then
                    isRunning = true
         
                    func(...)          -- Call it with the original arguments
         
                    isRunning = false
                end
            end
        end
         
        return debounce
    • Tree-collapse.png
      Part
      Button
      • Tree-collapse.png
        Script
        MyScript
          local debounce = require(game.Workspace.DebounceModule)
          script.Parent.Touched:connect(debounce(function(hit)
          	print("Button Touched")
          	wait(3)
          	print("Waited")
          end))
    • Tree-collapse.png
      Part
      Button2
      • Tree-collapse.png
        Script
        MyScript
          local debounce = require(game.Workspace.DebounceModule)
          script.Parent.Touched:connect(debounce(function(hit)
          	print("Button2 Touched")
          	wait(3)
          	print("Waited")
          end))

Advanced Example

Additionally, you can use ModuleScripts to load multiple variables, as long as the variables in the ModuleScript are not local. While this is quite useful, its important to note that the Script analysis does not respect this, and may falsely assume variables do not exist because they aren't loaded prior.

  • Tree-collapse.png
    Workspace
    Workspace
    • Tree-collapse.png
      ModuleScript
      LoadEnv
        local variableThatWontTransfer = "It transferred!"
         
        foo = 2
        bar = 4
         
        function fooBarTest()
        	print("FOOBAR")
        end
         
        -- Now return the function used to load the variables.
         
        return function() 
        	local myEnv = getfenv(1)				-- A table representing the environment of variables in the ModuleScript
        	local callingEnv = getfenv(2)			-- A table representing the environment of variables in the Script running the function.
        	for variable,value in pairs(myEnv) do	-- For each variable in our script environment
        		if variable ~= "script" then		-- Make sure we don't overwrite the "script" variable in the script requiring us.
        			callingEnv[variable] = value	-- Set 'variable' in the calling environment to the value of the variable in our environment.
        		end
        	end
        end
      • Tree-collapse.png
        Script
        TestScript
          require(script.Parent)() -- Loads the variables
           
          fooBarTest() -- Prints FOOBAR to the output.
          print(foo+bar) -- Prints '6' since foo = 4 and bar = 2
          print(variableThatWontTransfer) -- Prints 'nil' because "variableThatWontTransfer" was local, and thus wasn't visible in the global scope of the ModuleScript's environment.