I need to sort instances in a table

So for certain purposes, I have a ton of instances in a script that are named in order (name_0, name_1 name_2…), but when I use

	for i,v in pairs(script:GetChildren()) do
		print(v)
	end

then it comes up as a mixed order. I really need them to be in order from lowest to highest.

Try using ipairs and see if this works. Using pairs usually returns the array randomly. More information here pairs and ipairs | Roblox Creator Documentation

3 Likes

image
i just realized I used script:GetAttributeChangedSignal("Recording"):Connect(function() so it was firing twice lmao (yeah but i think from the way I generate the instances it auto sorts I think)

Order isn’t guaranteed this way. If you want a surefire way to get them in a certain order you could use table.sort, passing a function to compare the children like so, assuming all of the script’s children names follow a specific format:

local children = script:GetChildren()

table.sort(children, function(a, b)
    return tonumber(a.Name:gsub('name_', '')) < tonumber(b.Name:gsub('name_', ''))
end)

for _, child in children do...
-- or
for _, child in ipairs(children) do...

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