Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Help with looping through 2 things at once?

Man, been a while since I've been on here. I used to always be on here. I've got so much better at coding but I have one question. I know how to go about this but, I want an easier way. The code that is all commented out works but the code under it is what I was just testing.

Question: Is there a way to loop through "Character" and "Avatar" at once?

function ChangeBodyColor(Character,Avatar,BodyColor)
--	for i,Part in pairs(Character:GetChildren()) do
--		if Part:IsA('Part') then
--			Part.BrickColor = BrickColor.new(BodyColor)	
--		end
--	end
--	for i,Part in pairs(Avatar:GetChildren()) do
--		if Part:IsA('Part') then
--			Part.BrickColor = BrickColor.new(BodyColor)	
--		end
--	end

	for i,Part in pairs(Character:GetChildren(),Avatar:GetChildren()) do
		if Part:IsA('Part') then
			Part.BrickColor = BrickColor.new(BodyColor)	
		end
	end
end

1 answer

✓ Accepted answer

Yes.

The pairs iterator only takes one argument (a table). It wouldn't really make sense for your key : value pairs to represent different data at the same time by passing two tables.

Nested for loops

An alternative would be to use nested for loops. In other words, you'd be storing both your Character and Avatar tables inside another table, and traversing that. You'd still be using two for loops, but it would be infinitely expandable without needing to add more for loops for each table. For example...

-- t1 and t2 represent table1 and table 2
local function traverseGroup(t1, t2, ...)
	local group = {t1, t2} -- Pack tables into another table
	for _, t in next, group do
		for k, v in next, t do
			print("Pairs: ", k, v) -- This is where you'd be changing whatever
		end
	end
end

-- Using the table of children for each object
traverseGroup(Character:GetChildren(), Avatar:GetChildren())

The code above would print each key and value respectively in both tables. Like I said before, this is infinitely expandable. Say you wanted to do the same with 5 different tables...

local t1 = {"a", "b", "c"}
local t2 = {"d", "e", "f"}
local t3 = {"g", "h", "i"}
local t4 = {"j", "k", "l"}
local t5 = {"m", "n", "o"}

local function traverseGroup(...)
	local group = {...}
	for _, t in next, group do
		for k, v in next, t do
			print("Pairs: ", k, v) -- This is where you'd be changing whatever
		end
	end
end

traverseGroup(t1, t2, t3, t4, t5)

As expected, the first for loop would go through every pair inside group and the second for loop would go through every pair inside the current table in group. Visualizing it would look something like this.


Hope this helped, let me know if you have any questions.

This discussion is preserved as it was. New answers, comments, and votes are closed.