Running ipairs doesn't provide correct results, what am I missing?

Hello! I have a few lines of code that goes to a specific location and searches the contents using ipairs to put them in order and look through them one by one. The code works for numbers 01 - 03, skips to 06 and goes backwards to 04, then continues from 07 up to 12… Yea, confusing right?

Here is the code sample:

for i,v in ipairs(Inventory:GetChildren()) do
	if v:IsA("ImageButton") and v:WaitForChild("ToolName").Text == "" and Adding.Parent == Backpack then
		v.ToolName.Text = ToolName
		Adding.Parent = v
		wait()
		break
	end
end

Here is the location it is trying to sort through, which is located ultimately in the PlayerGui:

Screen Shot 2021-07-11 at 8.14.39 PM

I definitely feel like I’m overlooking something simple, and I feel as though the code had worked earlier today. This is the only code in my script that searches and sorts against this location.

Appreciate any help!
Romul

Something tells me that this might be a roblox thing, have you tried printing the object’s name inside of the loop to make sure that it isn’t roblox’ fault? since sometimes the gui elements get reorganized (to my knowledge) I might be wrong tho

:GetChildren() doesn’t automatically sort its children by name.
Try sorting the table first then looping through them.

2 Likes

Usually whenever you insert an object onto ROBLOX and call in ipairs, the first object you’ve inserted is usually to work first inside the loop

Duplicating that object in the Frame can have some wonky effects, perhaps temporary remove all of the ImageButtons from the Inventory Frame & try re-ordering them again properly

This was definitely the issue, and also as mentioned by Jackscarlett, the order would be based on insert. The more reliable way to always return what I needed was to create a table, sort the table, then go from there.

I accomplished it in the below code for anyone needing help with this in the future:

local TBL = Inventory:GetChildren()
table.sort(TBL,function(child1,child2)
	return tonumber(child1.Name) < tonumber(child2.Name)
end)
--print(TBL)
for i,v in ipairs(TBL) do
	if v:IsA("ImageButton") and v:WaitForChild("ToolName").Text == "" and Adding.Parent == Backpack then
		v.ToolName.Text = ToolName
		Adding.Parent = v
		wait()
		break
	end
end

Thanks!!!