How do I optimize this part grouping script?

i want to group multiple parts with different names into one model, which i have sort-of achieved using the following script:

for i,v in pairs(workspace:GetChildren())do
	if v.Name == "PartA" then
		v.Parent = workspace.Model
	elseif v.Name == "PartB" then
		v.Parent = workspace.Model
	elseif v.Name == "PartC" then
		v.Parent = workspace.Model
	elseif v.Name == "PartD" then
		v.Parent = workspace.Model
	elseif v.Name == "PartE" then
		v.Parent = workspace.model
	end
end

but i want to make this script more efficient, i.e use less lines of code.

i considered using table.find but i have no idea how to implement it into a script like this. are there other ways to reduce the lines of code on this?

2 Likes

Couldn’t you just do

if v.Name == “PartA”
or v.Name == “PartB”
or v.Name == “PartC”
or v.Name == “PartD”
or v.Name == “PartE”
then
v.Parent = workspace.Model
end

4 Likes

i am stupid for not realizing this sooner thanks though :slight_smile:

2 Likes

Tables might be a better fit here, instead of a stream of or statements.


local myParts = {
    ["PartD"] = true,
    ["PartA"] = true
}

if myParts[v.Name] then v.Parent = workspace.Model end

–edit–
It’s also a bit nit-picky, but as your “i” variable in your for loop is unused, you should really use ‘_’ instead.

1 Like

You could do this aswell:

for i, v in pairs(workspace:GetFullName()) do
	if v.Name:find("Part") then -- if finds "Part" in v.Name then (so this will work for anything that has Part in its name)
		v.Parent = workspace.Model
	end
end
3 Likes

Woah woah, WOW I did not know about this till today THANKS!

1 Like

Your welcome glad you learnt it. its very useful

1 Like

while it’s just as efficient as the other solution it’s convenient, which sort of makes it more efficient than the other solution. thank you very much