How do I get a single I,v pairs() loop to run through two different objects children

Reliable way to achieve this with the fewest gimmicks and least eye sore like code also I want it to run through one object first before running through the other one I don’t want them to both run ontop off each other

I haven’t tested this following code to see if it works but I assume it does (typed this on public transit) don’t tear it to shreds it’s just showcase of how i’de do this it’s far to ugly though ignore uppercase/lowercase

local objs = {workspace.BackP,workspace.Loot}

For a = 1,7^99 do task.wait(.5)
For _,V in ipairs(objs[a]:getchildren()) do
if a <= #obj then
warn(V) —or other code here—
end
Task.wait()
end
end

4 Likes

You could use a coroutine iterator to seamlessly zip together multiple tables. You can put this function inside a module so it can be used anywhere.

local function zip<T>(...: {T}): () -> (number, T)
	local tables: {{T}} = {...}
	return coroutine.wrap(function()
		local enumerate: number = 0
		for _, t in tables do
			for _, v in t do
				enumerate += 1
				coroutine.yield(enumerate, v)
			end
		end
	end)
end

for k, v in zip({1, 2, 3}, {4, 5, 6}) do
	print(k, v)
end

For your use case, do something like this:

for k, v in zip(part1:GetChildren(), part2:GetChildren(), part3:GetChildren()) do

end

And here’s an alternative version where it returns 3 values on each iteration; first one tells you which table it is iterating, second one is the index of that table, and third is the value.

local function zip<U, T>(...: {[U]: T}): () -> (number, U, T)
	local tables: {{[U]: T}} = {...}
	return coroutine.wrap(function()
		for which, t in tables do
			for k, v in t do
				coroutine.yield(which, k, v)
			end
		end
	end)
end

image

1 Like

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