Need help shortening my script

my code have 2k+ lines and i want to shorten it
yeah i have problems with finding and editing codes since there 2k+ lines

im thinking of putting functions into modules an then load them

please give me any possible ideas to shorten the code

2 Likes

i don’t know if shortening your code is the best idea to put into place here, i think organizing by putting them into functions that describe what it does in the name probably would be better. less code != better code

WAIT i just saw how many lines your script has :broken_heart:
but it would still be better to have more functions with good names to prevent repeating code which would probably shorten it and make it more concise and self explanatory on what everything does
if things are used across multiple scripts then modules would be a good fit too

1 Like

i actually add reusable functions, its just i put a lot of events in there
btw theres only one local script in my game :broken_heart:
i dont like having a lot of scripts

that should be against roblox tos :broken_heart:

2 Likes

ik please help :sob::sob::sob: dfigusdfkajhgjiofdvlkfjhgrjbifgrje

i would start from the top taking chunks of code that are common or complex and putting them into their own functions, in my opinion you shouldn’t have a module for one specific thing unless it’s a sort of system/utility/tool

1 Like

{BAA6734F-DC39-4BE9-9FD6-E0E9782A7745}
ig that you are using that local script for handling most of the stuff
you can add multiple scripts rather than one like “GuiHandler” “CharacterHandler” “SmtHandler” etc…

also you can press CTRL+ F to search for smt in the script

1 Like

please use more whitespace omg

anyway,
split your code into module scripts, and use stuff like BindableEvents (or simply do module.Function()) to run the things you need to run at any time you want

this is… really bad, just saying

2 Likes

This should only be done when your running decompilers :cry:

1 Like

Break it into modules and other local scripts

1 Like

You’d probably benefit from a Single Script Architecture instead of keeping everything inside that one local script.

1 Like

idk how does this work dfghjdmajvuigktjrksfjdv

Basically a Single Script Architecture is only having one Server Script and one Local Script, then through the local script you require what you need (Modules) an example would be like

--Client.lua (local script)

local HandleUserInput = require(script.UserInput)

HandleUserInput.ListenToEKey() -- This starts listening to the E Keycode

--UserInput.lua (Module Script)
local UserInputService = game:GetService("UserInputService")

function UserInput.ListenToEKey()
  UserInputService.InputBegan:Connect(function(input, gpe)
    if gpe then return end
    if input.KeyCode == Enum.KeyCode.E then
      print("E has been pressed")
    end
  end)
end

This is on the more intermediate side and a bare bones example, you could implement Object-Oriented Programming to further shorten it, but this will greatly reduce the amount of lines in your code.

1 Like

i have a lot of functions so how can i do this? there are a lot of variables i need to work with too

I don’t know how much you know about Module Scripts but this video by GnomeCode can greatly help you understand if you want to FURTHER module scripts you can learn OOP or Functional Programming. Start with this video, module scripts are just a organization tool mainly.

1 Like

This looks like an old school script doing everything at over 2000 lines… Now things are split up into remotes, functions and modules. I can’t see the whole script here and never work with pictures of a code.

I can see a few things here that could be done differently. Possibly a more top down approach to scripting would be my suggestion.

Declare variables
Write helper functions
Implement main logic
(optimize and refine)


(Ignore the duplicate EventsModule)

Most of these are for the server side, but this should apply to your client side stuff. Can’t go into much detail as I do not know what your client side is doing

I’ll give you GameState as an example, this module handles states related to the current round (it’s a round based game, plate of fate like)

local HttpService = game:GetService("HttpService")

local Utils = require(game.ReplicatedStorage.Modules.Utils)
local GAME_SETTINGS = require(game.ReplicatedStorage.GAME_SETTINGS)
local SignalModule = require(game.ReplicatedStorage.Modules.SignalModule)

local GameState = {}

local ActivePlayersFolder = game.ReplicatedStorage.ActivePlayers

local CurrentGamemode : string? = nil
local RoundId = nil
local ActivePlayers : {Player} = {}

local StartTime = 0

local Connections : {RBXScriptConnection} = {}

local GamemodeChangedEvent = Instance.new("BindableEvent")
GameState.GamemodeChangedEvent = GamemodeChangedEvent

-- This is called before GameState:StartRound(), but it is garanteed that GameState:StartRound() will be called after
function GameState:LoadPlayer(Player)

	if not Player or not Player.Parent then return false, nil end
	Player:LoadCharacter()
	
	local Character = Player.Character
	if not Character then return false, nil end

	local Humanoid = Character:FindFirstChild("Humanoid")
	if not Humanoid then return false, nil end

	local HumanoidRootPart = Character:FindFirstChild("HumanoidRootPart")
	if not HumanoidRootPart then return false, nil end

	Player:SetAttribute("Playing", true)

	local PlayingTag = Instance.new("ObjectValue", ActivePlayersFolder)
	PlayingTag.Value = Player
	PlayingTag.Name = Player.Name
	
	local CharacterTable = {
		Character = Character,
		HumanoidRootPart = HumanoidRootPart,
		Humanoid = Humanoid,
	}
	
	GameState.PlayerLoadedSignal:Fire(Player, CharacterTable)

	return true, CharacterTable
end

function GameState:StartRound(Gamemode : string, Players : {Player})
	
	GamemodeChangedEvent:Fire(CurrentGamemode)


	StartTime = os.clock()
	RoundId = HttpService:GenerateGUID(false)
	
	CurrentGamemode = Gamemode
	
	table.move(Players, 1, #Players, #ActivePlayers + 1, ActivePlayers)

	for _, Player in ipairs(Players) do
		table.insert(Connections, Player.CharacterRemoving:Connect(function()
			
			-- [...] - Doing stuff
			-- Cut out this bit as it isn't all that relevant and includes code examples that aren't ideal lol

		end))
	end
	
	GameState.GameStartedSignal:Fire()
end

function GameState:EndRound()
	
	GameState.GameEndingSignal:Fire()
	GamemodeChangedEvent:Fire(CurrentGamemode)

	
	StartTime = 0
	RoundId = nil
	
	CurrentGamemode = nil
	
	for _, Player in ipairs(ActivePlayers) do 
		Player:SetAttribute("Playing", false)
		Player.Team = game.Teams.Lobby
		Player:LoadCharacter()
	end
	
	table.clear(ActivePlayers)
	
	for _, v in ipairs(ActivePlayersFolder:GetChildren()) do
		v:Destroy()
	end

	for _, c in ipairs(Connections) do 
		c:Disconnect()
	end
end

function GameState:IsRoundActive()
	return RoundId ~= nil
end

function GameState:GetRoundId()
	return RoundId
end

function GameState:GetActivePlayers()
	return ActivePlayers
end

function GameState:SanitizeActivePlayersTable(ActivePlayers : {Player})
	local InvalidPlayers = {} -- Player no longer in game
	for i, Player in Utils.r_ipairs(ActivePlayers) do 
		if Player and Player.Parent then continue end
		table.insert(InvalidPlayers, Player)
		table.remove(ActivePlayers, i)
	end
	return ActivePlayers, InvalidPlayers
end

function GameState:IsPlayerActive(Player : Player)
	return table.find(ActivePlayers, Player) ~= nil
end

GameState.PlayerLoadedSignal = SignalModule.new()
GameState.PlayerDiedSignal = SignalModule.new()
GameState.GameStartedSignal = SignalModule.new()
GameState.GameEndingSignal = SignalModule.new()

function GameState:GetCurrentGamemode() : string?
	return CurrentGamemode
end

function GameState:GetRemainingTime()
	return math.clamp(GAME_SETTINGS.GAME_TIME_LIMIT - (os.clock() - StartTime), 0, GAME_SETTINGS.GAME_TIME_LIMIT)
end

function GameState:GetGameProgressionAlpha()
	return math.clamp(os.clock() - StartTime,0, GAME_SETTINGS.GAME_TIME_LIMIT)/GAME_SETTINGS.GAME_TIME_LIMIT
end

return GameState

You might notice that this module requires other modules, ie GAME_SETTINGS, Utils, and SignalModule. There is like a hierarchy of modules that forms, where those 3 above are at bottom, kind of the foundation, as they don’t require other modules, but are required a lot by other modules

In your case, it’ll probably be hard to separate your local script into modules, as I would assume, the code in your local script is probably all linked to each other, and so cutting 1 bit off and sending it into a module isn’t so feasible.
Using module scripts requires you to cut your code into structured blocks, that are mostly isolated from each other. This has many advantages, mainly that since the game is structured as isolated blocks of code, it is much easier to work on it, since you can focus on those blocks of code rather than the whole thing

So my question then is what’s the difference between bindable events and module scripts? Bindables are way easier to understand in my opinion so what would be the pros and cons of each? I know how to use both but I never really understood the difference since technically they both achieve the same result.

This is a good question! I guess it all comes down to the preference of the developer / development team.

I’m assuming with bindable events a con would be performance if you have a lot of them (If someone can benchmark this it would be amazing!) Even then for bigger systems its not really valid and could get messy.

While with module scripts you can directly reference the data it holds. Module scripts also encourage organized code, reusable code and returning complex things.

Bindable Event - “Which ever connection is listening, something happened and heres the data”
Module Script - “A toolbox with many tools inside of it.” (Functions, data, utility functions too.)

1 Like