How to access for loop variables from outside of a for loop

I am currently trying to create a for loop that will get all of the children of a folder, determine if the children are the correct child type, and then do stuff with that. I have 2 for loops (because you can’t have a for loop run inside of a for loop, right?) and I am trying to access the variables from the first one to the second one.

My code so far

for _, ObjectCategory in pairs(path:GetChildren()) do
	if ObjectCategory:IsA("Folder") then
		-- Do stuff
	end
end

for _, Objectin pairs(ObjectCategory:GetChildren()) do
	if Object:IsA("Model") then
        -- Do Stuff
	end
end

Any Ideas?

2 Likes

Why not just do:

for _, ObjectCategory in pairs(path:GetChildren()) do
	if ObjectCategory:IsA("Folder") then
       for _, Object in pairs(ObjectCategory:GetChildren()) do
	       if Object:IsA("Model") then
        -- Do Stuff
	        end
        end
	end
end

For clarity, when looping through each ObjectCategory, the code will also loop through all Object in that ObjectCategory before iterating over the next item (ObjectCategory) in the list.

4 Likes

Could be pretty expensive to loop through all that

1 Like

local tempTable = {} --create a table to hold all the folders

for _, ObjectVehicle in pairs(path:GetChildren()) do
	if ObjectCategory:IsA("Folder") then
		table.insert(tempTable, ObjectCategory)
	end
end

for _, Objectin pairs(tempTable) do
	if Object:IsA("Model") then --This will always return false tho
		-- do stuff here
	end
end
2 Likes

An alternative approach is to iterate through the descendants of an instance to a depth, d.

local recursion_depth: number = 2
local iterable: Instance = game.Workspace.Folder
local models = {}

function find_models(iter: Instance)
    if d > depth then return end
    depth += 1

    for k, v in pairs(iter:GetChildren()) do
        if v:IsA("Folder") then
            find_models()
            continue
        end

        if v:IsA("Model") then
            table.insert(models, v)
        end
end

find_models(iterable)
2 Likes

the meta

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