Is there any way to shorten this?

for Num, inst in ipairs(StartingPath:GetDescendants()) do
					if inst:IsA("Attachment") and inst.Name:lower() == "pathconnection" then
						ConnectableAttachments[inst] = {["FailedAttaches"] = 0}
					elseif inst:IsA("Attachment") and inst.Name:lower() == "wallconnection" then
						table.insert(ConnectableWallAttachments, inst)
					elseif inst:IsA("Part") and inst.Name:lower() == "pathsection" then
						table.insert(PathSections, inst)
					elseif inst:IsA("Part") and inst.Name:lower() == "floorconnection" then
						table.insert(FloorAttachments, inst)
					elseif inst:IsA("Part") and inst.Name:lower() == "roofconnection" then
						table.insert(RoofAttachments, inst)
					end
				end

Heres the code, it uses alot of elseif statements to check which attachment is which. i was wondering if theres a way i can shorten this

Use a dictionary with attachment names as indexes. You can also use functions as values.

1 Like

Thanks!, this did shorten it

local attachmentToTable = {
	["pathconnection"] = ConnectableAttachments,
	["wallconnection"] = ConnectableWallAttachments,
	["pathsection"] = PathSections,
	["floorconnection"] = FloorAttachments,
	["roofconnection"] = RoofAttachments
}
				
for Num, inst in ipairs(StartingPath:GetDescendants()) do
	if inst:IsA("Attachment") and inst.Name:lower() == "pathconnection" then
		ConnectableAttachments[inst] = {["FailedAttaches"] = 0}
	else
		if attachmentToTable[inst.Name:lower()] then
			table.insert(attachmentToTable[inst.Name:lower()], inst)
		end
	end
end
1 Like

Looks good, one optimization though so you don’t have to search the dictionary twice.

Code:

local attachmentToTable = {
	["wallconnection"] = ConnectableWallAttachments,
	["pathsection"] = PathSections,
	["floorconnection"] = FloorAttachments,
	["roofconnection"] = RoofAttachments
}

for Num, inst in ipairs(StartingPath:GetDescendants()) do
	local loweredName = inst.Name:lower()
	
	if inst:IsA("Attachment") and loweredName == "pathconnection" then
		ConnectableAttachments[inst] = {FailedAttaches = 0}
	else
		local attachmentTable = attachmentToTable[loweredName]
		
		if attachmentTable then
			table.insert(attachmentTable, inst)
		end
	end
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.