I want to learn how to use Module Scripts I do not know how
I looked at the Developer Hub and TheDevKing, AlvinBlox, GamerM8, I cannot understand them.
I need to know how to use Module Scripts because I cannot understand them in any way I only used them twice and I never understood them. Please if you could help me.
Assuming you understand how functions work, this is how I came to understand it. You can make a function or variable inside a module script, and it can be called or accessed from any other script with a reference to the module.
In it’s simplest form a module script has 2 things that differ it from a regular script
The ModuleScript will not run immediately, it will only run when another script calls require() on it
A ModuleScript returns something to the place it was called (this is incredibly useful
Example:
-- Server Script
local ModuleScript = require(game.ServerScriptService.ModuleScript) -- you must use require
-- now the ModuleScript "ModuleScript" will run
We required the ModuleScript so it runs
-- ModuleScript
print("Hello World") --> will print hello world once the module is required by the Script
local ValueToReturn = 50
return ValueToReturn -- this works like any return and return the value to where it was called
We write any code in the ModuleScript
Now back to the Server Script
-- Server Script
local WhateverTheModuleReturns = require(game.ServerScriptService.ModuleScript) -- you must use require
print(WhateverTheModuleReturns) --> 50, because that's what we returned in the ModuleScript
There’s really a third thing, which is that ModuleScripts can be run on the Server and on the Client (though they won’t share the same data)
-- ModuleScript
local testModule = {}
function testModule.printSomething(...)
print(...)
end
return testModule
-- ServerScript
local testModule = require(script.TestModule)
local printFunc = testModule.printSomething("String")
print(printFunc)
Yes that is a use of ModuleScripts, they are extremely useful because you access tables with functions or objects with properties and have them abstracted from your main code. And you can reuse them.
Thank you so much
This has made me so happy but I do have a question.
am I able to do stuff like countdowns? for I.G.
local module = {}
function module:Countdown(clock)
for i = 1,10,-clock do
print(i)
-- example: game.StarterGui.ScreenGui.TextLabel.Text = i
wait(clock)
end
end
return module
-- ServerScript
local module = require(script.Module)
module.Countdown()