How to correctly list parts in a model

Im trying to make parts get correctly noted down (i.e. in an order)
image

ive tried both GetDescendants and GetChildren, but they always end up listing them in the wrong order (i.e. PartAAa, PartAAc, PartAAh, Part AAb. . .)

i havent found what i have been searching for yet (and i really dont want to hardcode the parts, as i will have over 100 parts that i would have to hardcode)

3 Likes

You can always GetChildren() and then sort them using some algorithm like Merge Sort or Quick Sort.

Simplest solution (table.sort uses Quick Sort):

local parts = model:GetChildren();
table.sort(parts, function(a, b) return a.Name < b.Name end)
8 Likes

Other solution is to insert the parts into the model in the order you want, because that is the order that will be returned with GetChildren().

The children are sorted by the order in which their Parent property was set to the object.

Source: Instance | Documentation - Roblox Creator Hub

4 Likes

ah, i guess that works, ill keep this open though incase someone has a less labor-intensive method

for _,part in pairs(Model:GetChildren()) do
print(part.Name)
end

This should be in alphabetical order, as roblox organizes children that way.

Edit: It is returned in order added.

See @ThousandDegreeKnife’s response instead.


If you’d like, you can implement your own alphabetical sort similar to this one I wrote for the sake of example:

local function alphabeticalSort(name1, name2)
	
	if (#name1 ~= #name2) then -- If one name is shorter than another
		return #name1 < #name2
	end
	
	
	local positionInWord = 1
	for i in name1:gmatch("%w") do
		local letterOfName1 = i
		local letterOfName2 = name2:sub(positionInWord, positionInWord)
		
		if (letterOfName1 ~= letterOfName2) then -- If our letters are different
			return letterOfName1:byte() < letterOfName2:byte() -- Which letter has the lowest ASCII decimal representation (they're ordered alphanumerically)
		end	
		
		positionInWord = positionInWord + 1
	end
	
end

and example of its use being:

local t = {"PartAAc", "PartAAb", "PartAAa", "PartAA"}

table.sort(t, alphabeticalSort)

print("{"..table.concat(t, ", ").."}") -- >  {PartAA, PartAAa, PartAAb, PartAAc}

Given that GetChildren returns instances & not strings, you’d need to modify the sort to operate upon the instance’s names

Simplest way is close to @Kacper’s solution:

1 Like

Wow! Cool, I had no idea that the relation operators < & > operated that way upon strings; do you know where this behavior is documented?

It is documented here: Programming in Lua : 3.2

1 Like

I mean i know im late but. You can name your parts p1, p2. Then make a for loop of the size #children
Then just get the part by doing p[i] and u get the right order. Only problem is you have to name all the parts. But it looks like you did that already anyway.