How can I make for i,v in ipairs() loops more Efficient?

I Would like to achieve a more efficient way to do a

for i, v in ipairs()

loop

This script below is an example of how I would use it (I use it a lot) and was wondering if there’s a more efficient way, so I don’t have to write the loop 4 times
Thanks

– Aqqua

for _, GUI in ipairs(PlayerGUI:GetChildren()) do
	for _, Frame in ipairs(GUI:GetChildren()) do
		for _, Textlabel in ipairs(Frame:GetChildren()) do
			for _, UIStroke in ipairs(Textlabel:GetChildren()) do
				
			end
		end
	end
end
1 Like

I don’t think so. You could use :GetDescendants on the PlayerGui then do v:IsA to check its class but this is really only if you want it to check and apply something to each descendant.

for i, v in ipairs(PlayerGUI:GetDescendants()) do
    if (v:IsA("UIStroke")) then
        -- do smth
    end
end
2 Likes

Going further, ipairs is fundamentally slower than just pairs, so you (@AqquaDev) should be using pairs here as you don’t care about the order of the Descendants.

Additionally, with Luau, you can drop the pairs entirely and just iterate over the Table returned by GetDescendants directly:

for _, v in PlayerGUI:GetDescendants() do
    if (v:IsA("UIStroke")) then
        -- do something
    end
end

It used to be and is in vanilla Lua 5.1, but Roblox fixed it.

Be very careful with your wording, efficient and clean have different meanings, and half the time they are mutually exclusive. Truly efficient code is not always easy to read, and clean code isn’t always so efficient.

1 Like

The other part of my reply there is still relevant: you should use pairs when you don’t [need to] care about the order you iterate over the Table, and ipairs if you do, or if there are non-numeric elements you wish to skip in a mixed Table.

1 Like

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