Code clean up (200+ lines)

This is my original code and I’d like to clean it up a lil cuz it seems really messy.

local MasterSwitch = script.Parent.MasterSwitch

local MasterSwitchColors = {
	Ready = Color3.fromRGB(81, 236, 135);
	InUse = Color3.fromRGB(247, 82, 82); -- Old color: 231,69,0
};

local BaseFrame = script.Parent.BaseFrame

local BaseFramePositions = {
	Out = UDim2.new(0.367, 0,0.793, 0);
	In = UDim2.new(0.367, 0,1, 0);
};

local Activated = false

local db = false

local RS = game:GetService("ReplicatedStorage")

local Shapes = RS.Shapes

local TestParts = workspace.TestParts

local TestPartSpawnPositions = workspace.TestChamber.TestPartSpawnPositions

local AvailableColors = {
	"Red";
	"Orange";
	"Yellow";
	"Green";
	"Blue";
	"Magenta";
};

local ColorValues = {
	["Red"] = Color3.fromRGB(255, 58, 58);
	["Orange"] = Color3.fromRGB(255, 87, 57);
	["Yellow"] = Color3.fromRGB(255, 242, 56);
	["Green"] = Color3.fromRGB(73, 255, 79);
	["Blue"] = Color3.fromRGB(38, 85, 255);
	["Magenta"] = Color3.fromRGB(170, 0, 170);
};

local function ChooseTestPartSpawnPos()
	
	local xMin = math.min(TestPartSpawnPositions.X1.Position.X,TestPartSpawnPositions.X2.Position.X)
	
	local xMax = math.max(TestPartSpawnPositions.X1.Position.X,TestPartSpawnPositions.X2.Position.X)
	
	local zMin = math.min(TestPartSpawnPositions.Z1.Position.Z,TestPartSpawnPositions.Z2.Position.Z)
	
	local zMax = math.max(TestPartSpawnPositions.Z1.Position.Z,TestPartSpawnPositions.Z2.Position.Z)
	
	return Vector3.new(math.random(xMin,xMax),207.5,math.random(zMin,zMax))
	
end

local function AddCommas(num)
	
	local formatted = tostring(num)
	
	while true do
		
		formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
		
		if k == 0 then
			
			break
			
		end
		
	end
	
	return formatted
	
end

local ProgDisplay = BaseFrame.ProgBarHolder.ProgDisplay

local ProgPercentDisplay = BaseFrame.ProgBarHolder.ProgPercentDisplay

local GearIcon = BaseFrame.GearIcon

local plr = game.Players.LocalPlayer

local SetTestingStatus = RS.RemoteEvents.SetTestingStatus

MasterSwitch.MouseButton1Click:Connect(function()
	
	if not db then
		
		db = true
		
		if not Activated then
			
			MasterSwitch.BackgroundColor3 = MasterSwitchColors.InUse

			local TS = game:GetService("TweenService")

			local TweenStyle1 = TweenInfo.new(0.3,Enum.EasingStyle.Quart,Enum.EasingDirection.InOut) -- For base frame

			local Tween = TS:Create(BaseFrame,TweenStyle1,{Position = BaseFramePositions.Out})
			Tween:Play()

			Tween.Completed:Wait()
			
			SetTestingStatus:FireServer(true)

			Activated = true
			
			db = false
			
			BaseFrame.TaskDisplay.Text = "GENERATING..."
			
			local TweenStyle2 = TweenInfo.new(0.2,Enum.EasingStyle.Sine,Enum.EasingDirection.InOut) -- For the progress bar
			
			coroutine.resume(coroutine.create(function()
				
				local RunService = game:GetService("RunService")
				
				RunService.Heartbeat:Connect(function()

					if #TestParts:GetChildren() > 0 then

						GearIcon.Rotation += 0.4

					else

						GearIcon.Rotation = 0

					end
					
				end)
				
			end))
			
			repeat

				if #TestParts:GetChildren() < 30000 then

					local ChosenShapeColor = AvailableColors[math.random(1,#AvailableColors)]

					local ChosenShape = Shapes:GetChildren()[math.random(1,#Shapes:GetChildren())]:Clone()
					ChosenShape.Color = ColorValues[ChosenShapeColor]

					ChosenShape.Parent = TestParts
					
					ChosenShape.Material = Enum.Material[plr.Mod.Value]

					ChosenShape.Position = ChooseTestPartSpawnPos()
					
					ProgDisplay.Text = AddCommas(#TestParts:GetChildren()) .. "/30,000"
					
					ProgPercentDisplay.Text = tostring(math.floor((#TestParts:GetChildren() / 30000) * 100)) .. "%"
					
					BaseFrame.ProgBarHolder.Bar.BackgroundColor3 = Color3.fromRGB(247, 82, 82):Lerp(Color3.fromRGB(81, 236, 135),#TestParts:GetChildren() / 30000)
					
					TS:Create(BaseFrame.ProgBarHolder.Bar,TweenStyle2,{Size = UDim2.new((#TestParts:GetChildren() / 30000),0,1,0)}):Play()
					
				end

				task.wait(0.1)

			until not Activated or (#TestParts:GetChildren() == 30000)

			-- Cleaning up

			if #TestParts:GetChildren() > 0 then
				
				BaseFrame.TaskDisplay.Text = "CLEANING..."
				
				local TotalParts = #TestParts:GetChildren()
				
				local PartsDeleted = 0
				
				for _, Part in pairs(TestParts:GetChildren()) do
					
					Part:Destroy()
					
					PartsDeleted = TotalParts - #TestParts:GetChildren()
					
					ProgDisplay.Text = AddCommas(PartsDeleted) .. "/" .. AddCommas(TotalParts)

					ProgPercentDisplay.Text = tostring(math.floor((PartsDeleted / TotalParts) * 100)) .. "%"
					
					BaseFrame.ProgBarHolder.Bar.BackgroundColor3 = Color3.fromRGB(247, 82, 82):Lerp(Color3.fromRGB(81, 236, 135),PartsDeleted / TotalParts)
					
					TS:Create(BaseFrame.ProgBarHolder.Bar,TweenStyle2,{Size = UDim2.new((PartsDeleted / TotalParts),0,1,0)}):Play()

					task.wait(0.05)

				end

			end
			
			if Activated then Activated = false end
			
			BaseFrame.TaskDisplay.Text = ""
			
			MasterSwitch.BackgroundColor3 = MasterSwitchColors.Ready
			
		else
			
			SetTestingStatus:FireServer(false)
			
			Activated = false
			
			if #TestParts:GetChildren() > 0 then
				
				repeat task.wait() until #TestParts:GetChildren() == 0
				
				db = false
				
			end
			
		end
		
	end
	
end)

BaseFrame.ProgBarHolder.MouseEnter:Connect(function()
	
	ProgDisplay.Visible = false
	
	ProgPercentDisplay.Visible = true	
	
end)

BaseFrame.ProgBarHolder.MouseLeave:Connect(function()

	ProgDisplay.Visible = true

	ProgPercentDisplay.Visible = false	

end)

Your spacing makes the script very long. You should only have extra line spaces when you have different statements than other ones or return statements. Check this page out for more on style guides:

https://roblox.github.io/lua-style-guide/

Additionally you can always right click and format the code.

Ideally move things like plr variable, service and instance definitions (example: remote events) to the top instead of placing them in between the functions. With a good style it’s also easy to avoid things like debounce variables.

I see other issues like potential memory leaks in your code as well but since it’s not related with the post that’s pretty much all I can say about cleaning up.

3 Likes

Here is an example of some changes:

-- Services
local ReplicatedStorage: ReplicatedStorage = game:GetService("ReplicatedStorage")
local TweenService: TweenService = game:GetService("TweenService")
local RunService: RunService = game:GetService("RunService")

-- References
local MasterSwitch: ImageButton = script.Parent.MasterSwitch
local BaseFrame: Frame = script.Parent.BaseFrame
local ProgDisplay: TextLabel = BaseFrame.ProgBarHolder.ProgDisplay
local ProgPercentDisplay: TextLabel = BaseFrame.ProgBarHolder.ProgPercentDisplay
local GearIcon: ImageLabel = BaseFrame.GearIcon
local TestParts: Folder = workspace.TestParts
local TestPartSpawnPositions: Folder = workspace.TestChamber.TestPartSpawnPositions
local Shapes: Folder = ReplicatedStorage.Shapes
local SetTestingStatus: RemoteEvent = ReplicatedStorage.RemoteEvents.SetTestingStatus

-- Constants
local MasterSwitchColors: { [string]: Color3 } = {
	Ready = Color3.fromRGB(81, 236, 135),
	InUse = Color3.fromRGB(247, 82, 82),
}

local BaseFramePositions: { [string]: UDim2 } = {
	Out = UDim2.new(0.367, 0, 0.793, 0),
	In = UDim2.new(0.367, 0, 1, 0),
}

local AvailableColors: { [number]: string } = {
	"Red", "Orange", "Yellow", "Green", "Blue", "Magenta"
}

local ColorValues: { [string]: Color3 } = {
	Red = Color3.fromRGB(255, 58, 58),
	Orange = Color3.fromRGB(255, 87, 57),
	Yellow = Color3.fromRGB(255, 242, 56),
	Green = Color3.fromRGB(73, 255, 79),
	Blue = Color3.fromRGB(38, 85, 255),
	Magenta = Color3.fromRGB(170, 0, 170),
}

-- Variables
local plr: Player = game.Players.LocalPlayer

-- State Pattern
local State = {}
State.__index = State

function State.new(name: string, color: Color3, position: UDim2): State
	local self = setmetatable({}, State)
	self.name = name
	self.color = color
	self.position = position
	return self
end

function State:Enter()
	MasterSwitch.BackgroundColor3 = self.color
	local Tween: Tween = TweenService:Create(BaseFrame, TweenInfo.new(0.3, Enum.EasingStyle.Quart, Enum.EasingDirection.InOut), {Position = self.position})
	Tween:Play()
	Tween.Completed:Wait()
end

local ReadyState: State = State.new("Ready", MasterSwitchColors.Ready, BaseFramePositions.In)
local InUseState: State = State.new("InUse", MasterSwitchColors.InUse, BaseFramePositions.Out)

local CurrentState: State = ReadyState

-- Functions
local function ChooseTestPartSpawnPos(): Vector3
	local xMin: number = math.min(TestPartSpawnPositions.X1.Position.X, TestPartSpawnPositions.X2.Position.X)
	local xMax: number = math.max(TestPartSpawnPositions.X1.Position.X, TestPartSpawnPositions.X2.Position.X)
	local zMin: number = math.min(TestPartSpawnPositions.Z1.Position.Z, TestPartSpawnPositions.Z2.Position.Z)
	local zMax: number = math.max(TestPartSpawnPositions.Z1.Position.Z, TestPartSpawnPositions.Z2.Position.Z)
	return Vector3.new(math.random(xMin, xMax), 207.5, math.random(zMin, zMax))
end

local function AddCommas(num: number): string
	local formatted: string = tostring(num)
	while true do
		formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
		if k == 0 then break end
	end
	return formatted
end

local function UpdateProgressBar(current: number, total: number)
	ProgDisplay.Text = AddCommas(current) .. "/" .. AddCommas(total)
	ProgPercentDisplay.Text = tostring(math.floor((current / total) * 100)) .. "%"
	local progress: number = current / total
	BaseFrame.ProgBarHolder.Bar.BackgroundColor3 = Color3.fromRGB(247, 82, 82):Lerp(Color3.fromRGB(81, 236, 135), progress)
	TweenService:Create(BaseFrame.ProgBarHolder.Bar, TweenInfo.new(0.2, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut), {Size = UDim2.new(progress, 0, 1, 0)}):Play()
end

local function GenerateTestParts()
	BaseFrame.TaskDisplay.Text = "GENERATING..."
	repeat
		if #TestParts:GetChildren() < 30000 then
			local ChosenShapeColor: string = AvailableColors[math.random(1, #AvailableColors)]
			local ChosenShape: BasePart = Shapes:GetChildren()[math.random(1, #Shapes:GetChildren())]:Clone()
			ChosenShape.Color = ColorValues[ChosenShapeColor]
			ChosenShape.Parent = TestParts
			ChosenShape.Material = Enum.Material[plr.Mod.Value]
			ChosenShape.Position = ChooseTestPartSpawnPos()
			UpdateProgressBar(#TestParts:GetChildren(), 30000)
		end
		task.wait(0.1)
	until CurrentState ~= InUseState or (#TestParts:GetChildren() == 30000)
end

local function CleanUpTestParts()
	BaseFrame.TaskDisplay.Text = "CLEANING..."
	local TotalParts: number = #TestParts:GetChildren()
	local PartsDeleted: number = 0
	for _, Part: BasePart in pairs(TestParts:GetChildren()) do
		Part:Destroy()
		PartsDeleted = TotalParts - #TestParts:GetChildren()
		UpdateProgressBar(PartsDeleted, TotalParts)
		task.wait(0.05)
	end
end

local function ToggleActivation()
	if CurrentState == ReadyState then
		CurrentState = InUseState
		CurrentState:Enter()
		SetTestingStatus:FireServer(true)
		GenerateTestParts()
		if #TestParts:GetChildren() > 0 then
			CleanUpTestParts()
		end
		CurrentState = ReadyState
		CurrentState:Enter()
		BaseFrame.TaskDisplay.Text = ""
	else
		SetTestingStatus:FireServer(false)
		CurrentState = ReadyState
		CurrentState:Enter()
		if #TestParts:GetChildren() > 0 then
			repeat task.wait() until #TestParts:GetChildren() == 0
		end
	end
end

-- Event Connections
MasterSwitch.MouseButton1Click:Connect(ToggleActivation)

RunService.Heartbeat:Connect(function()
	if #TestParts:GetChildren() > 0 then
		GearIcon.Rotation += 0.4
	else
		GearIcon.Rotation = 0
	end
end)

BaseFrame.ProgBarHolder.MouseEnter:Connect(function()
	ProgDisplay.Visible = false
	ProgPercentDisplay.Visible = true
end)

BaseFrame.ProgBarHolder.MouseLeave:Connect(function()
	ProgDisplay.Visible = true
	ProgPercentDisplay.Visible = false
end)
1 Like