Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How can i use a Module script to make my code more organised and efficient?

Asked by 6 years ago

Hello, I'm working on my NPC for my game and so far have achieved awesome progress it works flawlessly as of so far however, to make it easier for my self i'd love to get into Module scripts as that will allow me to easily navigate through my code when it comes to error fixing and adding code in general. The issue is, where do i get started? I understand the practicality of module scripts but when i open up one of those scripts i feel really awkward on how to use them.

Here is all my code for the NPC for those who are interested:

-Controller

01local Event = script.Parent:WaitForChild("findTarget")
02 
03local npcStorage = workspace.Game.npcStorage
04 
05while true do wait(1)
06    if #npcStorage:GetChildren() >0 then
07        Event:FireServer()
08    else
09        script.Parent:WaitForChild("Target").Value = ""
10    end
11end

-TargetFinder

01local Event = script.Parent:WaitForChild("findTarget")
02 
03Event.OnServerEvent:Connect(function() 
04    local NPC = script.Parent.Parent   
05    local myTeam = NPC.AI:WaitForChild("Team")
06    local HRP = NPC:WaitForChild("HumanoidRootPart")
07 
08 
09    local Target = NPC.AI:WaitForChild("Target")   
10    local NPCs = workspace.Game.npcStorage
11 
12 
13    local closestTarget = nil
14    local targetsDistance = nil
15 
View all 31 lines...

-Movement

01local atkDistance = 3.5
02local Tower = workspace.Game:FindFirstChild("RedTower")
03 
04 
05 
06--/// myNPC
07local NPC = script.Parent.Parent
08    local HRP = NPC:WaitForChild("HumanoidRootPart")
09    local Hum = NPC:WaitForChild("Humanoid")
10 
11    local AI = NPC:WaitForChild("AI")
12    local Team = AI:WaitForChild("Team")
13    local Target = AI:WaitForChild("Target")   
14    local moveToTower = AI:WaitForChild("moveToTower"
15 
View all 44 lines...

If you need to know any more information please let me know. And thankyou if you can explain how to use Module Scripts.

0
Modules are like bindable functions. They can be passed using seperate scripts. To get a module script's and all of it's function, use "require(moduleplacing)". I'd show you mine but i'm new to scripting helpers and idk how to post scripts. Anyways, you give the module a name, "local Object = {}" then a function inside like "function Object.NAME()" then call it from another script. Delude_d 112 — 6y
0
You call it using the variable name that requires the module, like "Object = require(module)". Then, to call a function, do "Object.FunctionName(arguments)". Modules are very simple. Delude_d 112 — 6y
0
You really shouldn't have the client telling the server when npcStorage has stuff. hiimgoodpack 2009 — 6y

3 answers

Log in to vote
1
Answered by 6 years ago
Edited 6 years ago

ModuleScript objects have default code already pasted, similar to Scripts and LocalScripts how they have print("Hello world") as the default code. This is the default code for modules:

1local module = {}
2 
3return module

Modules act like a function in a way. It must be called. Modules are basically tables, which will be returned, so we can index objects inside the table. Take this for example:

1local module = {} -- You can name them anything, I just used the default name
2 
3function module.functionInModule()
4    print("I’m a function inside a module!")
5end
6 
7 
8 
9return module -- required to work

Functions inside modules MUST be global, cannot be local. You make it local by adding the keyword local before function. local function

From your server/local script:

1local module = require(game.Workspace.ModuleScript) -- i put in workspace
2 
3module.functionInModule() -- prints code

A cool thing to note about ModuleScripts is that they take on the behaviour of a Script or a LocalScript, depending on what you use. For example, if you used LocalPlayer in a module, you MUST require it from a LocalScript else the script will error and LocalPlayer will return nil, since LocalPlayer is client-side only.

Ad
Log in to vote
2
Answered by
amanda 1059 Moderation Voter
6 years ago

Hello there! I am excited that you are giving ModuleScripts a chance for the sake of organization.

Although there are good practices and bad practices many people use modules to a different extent, because as is with a normal script, it heavily depends on your coding style and how much code you can handle in your regular scripts before you consider it unorganized.

With that in mind, first I will teach you the basic functionality of a module, and then I will show you how I use modules.

--

A module is like any other script, the code in it runs from top to bottom, and it only runs once.

If you have a loop inside it, that loop will obviously still loop, but a ModuleScript is not a function that you call.

The primary differences are as follows:

  • it does not run until the first time it is required
  • at the very end of the ModuleScript, you must return exactly one value

Module Script

1print("ModuleScript is running")
2 
3return true

"Normal" (Server) Script

1local testing = require(script.Testing) --> true
2 
3if testing then
4    print("TEST MODE ACTIVATED!")
5else
6    print("THIS IS NOT A DRILL!")
7end

In this example, all the module does is print that it is running, and then returns true. In this case, I am letting the script that is requiring it know that the game is currently in "test mode", whatever that means.

With that being said, you can require the same module in multiple scripts, and then they will all know that the game is in test mode. If you want to change the test mode, you just have to change it in the module, and not have to worry about each individual script.

Module Script

01local quickmaths = {}
02 
03quickmaths.Add = function(a, b)
04    if a and b then
05        local res = a + b
06        print(("%d + %d = %d"):format(a, b, res))
07        return res
08    else
09        print("2 + 2 = 4")
10        return 2 + 2
11    end
12end
13 
14quickmaths.Subtract = function(a, b)
15    if a and b then
View all 26 lines...

"Normal" (Server) Script

1local quickmaths = require(script.quickmaths)
2 
3local seven = quickmaths.Add(5, 2)     
4local four = quickmaths.Subtract(seven, 3)
5 
6quickmaths.Add()
7quickmaths.Subtract()

Here, you should be able to see the difference. I've moved a table of custom math methods into a module, thus organizing my code.

ModuleScripts are extensions of normal scripts. You can throw the clutter in them. Functions, tables, math, libraries. What does that leave your normal script looking like?

If you've done it right, at the end of it all, it is short, readable, and easy to understand the flow of the game.

--

Final notes:

  • The return value of a module script is cached.
  • Modules run in the environment you require them in. If you put a module in ReplicatedStorage, it is copied to both the Client and the Server, however editing it will be editing their separate copies and is not a means to send messages without remotes.

Contact me on Discord if you have any questions, or would like more information about modules that I have not provided in this answer. My Discord tag is amanda#9999.

Log in to vote
0
Answered by
Delude_d 112
6 years ago
Edited 6 years ago
01local Object = {}
02 
03--------------- Function.Waves(BrickColor.new("Cyan"), Torso, 1, 0.5)
04 
05local Effects = game:GetService("ServerStorage"):WaitForChild("Skills")
06local Meshes = Effects:WaitForChild("Assets")
07local Parts = workspace:WaitForChild("PartStorage")
08local rep = game:GetService("ReplicatedStorage")
09local Assets = rep:WaitForChild("Assets")
10local auras = rep:WaitForChild("Aura")
11local auras2 = rep:WaitForChild("WideAuras")
12 
13----------- DUST 2.0
14function Object.Dust(root, duration)
15    local dust = Assets.Dust:Clone()
View all 31 lines...

Answer this question