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

How would I implement a complete iteration over the workspace?

Most of you may think that I am simply talking about a generic for loop like so:

for i,v in pairs(workspace:GetChildren()) do
	print(v.Name);
end

However, this will only iterate through every single child of workspace; what if I had a folder or a model containing more parts and objects? and what if I had a folder or another model inside of that folder/model with more objects? Essentially I am trying to figure out if there is a way to do a full loop over everything in the workspace, including all descendants of the workspace. i.e objects contained in a folder or model, and that folder/model is a child or descendant of the workspace. If anyone has a solution please let me know!

1 answer

✓ Accepted answer

Not sure why you want to do this, as this can be quite laggy (if your workspace contains a lot of stuff).

Anyhow,

You can put the for loop in a function and then call the function fromout of the for loop. The following function will return every instance in a table.

function GetDescendants(o)
	local allObjects = {}
	function FindChildren(Object)
	   for _,v in pairs(Object:GetChildren()) do
			table.insert(allObjects,v)
	        FindChildren(v)
	    end
	end
	FindChildren(o)
	return allObjects
end

local allObjects = GetDescendants(workspace)

5 comments

1

That's called a recursive function, by the way.

0

thanks! Basically I am making a ROBLOX framework, and i need to be able to get all descendants and check that they are present in the initialization stage.

1

Iteration is also a viable option over recursion, for a deep recursive process can burn through a lot of memory assigning a new address to each level. This is the same reason you can get the infamous stack overflow error from infinite recursion.

1

I think there's a solution to that called "tail-end return". I could be mistaken, though.

0

I just hope people know to don't use global variables.

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