For Loops [ASKING OPINION]

Is it better to use

local child = player.Character:GetChildren() 
for i=1, #child do 
	if (child[i].className == "Accessory") then 
		child[i]:Destroy() 
	end 
end

or

local child = player.Character:GetChildren() 
for i, v in pairs(child) do 
	if (child.className == "Accessory") then 
		child:Destroy() 
	end 
end

Or is it the same?

3 Likes

i think is the same, but I was told that “ipairs” is better optimized than “pairs”

1 Like

Personally I normally use method 2 more than method 1

1 Like

Believe they are generally the same, I’d use method#2 as well and see method#2 in more posts than other methods.

So far I’d say whichever is easiest to read for the project.

But for function, processing is the same right?

I prefer the second way, generally because it makes life easier. It makes everything more simple, especially if I am doing more complex stuff.

for i = 1, #child do

Is a numeric for loop. The simplest type of a loop, only needs 2 or 3 arguments. All three expressions are evaluated once, before the loop starts. And the control variable (i) is a local variable automatically declared by the for statement and is visible only inside the loop.

for i, v in pairs(child) do

Is a generic for loop. A more powerful and advanced type of a for loop. With this, you could traverse or loop through almost anything. And the bonus is, you could achieve that in a readable fashion.


I would personally use a generic for loop because it’s more readable and easier (for me personally) to use.

To read more about numerical for loops and generic for loops, search up “lua.org for loops”

In the original Lua language, ipairs was actually slower than pairs. But now with Luau (Roblox’s programming language derived from Lua) actually makes ipairs faster than pairs.

And just another thing to note here, pairs() is used with dictionaries, and ipairs() is used with arrays.

1 Like

But there’s no problem if i use ipairs for dictionarios and instances too?

2 Likes

ipairs will only go through keys that are numbers.

local table = {A = 1, 4, B = 2, 5, C = 3, 6}
for i, v in ipairs(table) do
	print(i,v)
end
-- 1 4
-- 2 5
-- 3 6

That code only printed the keys that are numbers

local table = {
	A = 1,
	4,
	B = 2,
	5,
	C = 3,
	6,
}
-- Organize the table (visually)
table = {
	A = 1,
	B = 2,
	C = 3,
	4,
	5,
	6,
}
-- it only prints 4, 5, 6
3 Likes

It’d be better to use ClassName as className is deprecated.

https://developer.roblox.com/en-us/api-reference/property/Instance/className

For your snippet of code I’d call the :RemoveAccessories() instance method on the character’s humanoid instance in order to remove its accessories.

local players = game:GetService("Players")
local player = players.LocalPlayer
local character = player.Character
local humanoid = character:WaitForChild("Humanoid")
humanoid:RemoveAccessories()