Loop from the bottom!

So basically, I was just wondering you could get a for i,v in pairs loop to loop from the bottom, instead of the top, I will be showing it down below.

As you may see, I want the for i,v in pairs loop to go from the bottom, to the top, instead of the loop going from the top, to the bottom!

2 Likes

GetChildren() Will get a table containing all the children so you can use ipairs to loop over it in an order:

for i,v in ipairs(tbl) do

if you want this to run backwards you can reverse the table by (shamelessly stolen from one of buildthomas’s answers!):

local tbl = x:GetChildren()
for i = 1, math.floor(#tbl/2) do
   local j = #tbl  - i + 1
    tbl[i], tbl[j] = tbl[j], tbl[i]
end

for i,v in ipairs(tbl) do
    print(v.Name)
end

I would be interested in your use case, though, since there might be a more efficient way to do this as GetChildren() can change order if you un-parent/re-parent instances.

2 Likes

Alternatively, you could simply use a Numeric For Statement.

local t = {5, 4, 3, 2, 1}

for i = #t, 1, -1 do
	print(t[i])
end
5 Likes

My elegant solution.


local Elements = game.Workspace.Folder:GetChildren() -- Replace with your folder containing your elements/objects/children!

local InverseIndex = #Elements

for i = InverseIndex, 1, -1 do
	local object = Elements[i]
	print(object.Name)
	-- do other stuff lol
end

7 Likes