Any improvements on my weld script?

Hi. I made a weld script. Is there anything that could be better about this?

local parts = script.Parent:GetDescendants() --collect all parts

for k,v in pairs(parts) do --remove any non-parts
  if v.ClassName ~= "Part" and v.ClassName ~= "WedgePart" and v.ClassName ~= "CornerWedgePart" then
    table.remove(parts, k)
  end
end

local randomKey = math.random(1, #parts) --select a key
local base = parts[randomKey] --use key to select a random part as a base
table.remove(parts, randomKey) --remove base from parts list to prevent welding to self

local welds = Instance.new("Model", script.Parent) --make a model to organize welds better
welds.Name = "welds"

for k,v in pairs(parts) do --weld everything to base
  local weld = Instance.new("WeldConstraint")
  weld.Parent = welds
  weld.Part0 = base
  weld.Part1 = v
end

for k,v in pairs(parts) do --unanchor everything
  v.Anchored = false
end
base.Anchored = false

The use of two loops – one to remove non-parts and one to weld the rest – seems inefficient to me at first glance.

I feel like it would be better to use FindFirstChildWhichIsA() to get the weld base, rather than looping through descendants to remove non-parts then choosing a random part to serve as the base.

That way you can still loop through the descendants afterwards as normal, just including the part-check in the one loop.

2 Likes

You can use Instance’s IsA() method to check the classname of a part.

for k, v in pairs(parts) do
    if(not v:IsA("BasePart")) then  -- Check if the part's class doesn't extend BasePart
        table.remove(parts, k)
    end
end

If the parent of the script is a Model, then you can set script.Parent.PrimaryPart as the base weld part, and use it instead of a random part to weld it to.

One question I have is why are you unanchoring parts?
Other than that, the code is okay.

I’m unanchoring parts because they are all initially anchored so that they don’t change positions before the script runs.