How does recursion work?

I’m interested in recursion. But this code Roblox gets has me some questions.

function colorAllParts(object, brickColor)
	if object:IsA("BasePart") then
		object.BrickColor = brickColor
	end
	for _, child in ipairs(object:GetChildren()) do
		colorAllParts(child, brickColor)
	end
end
 
colorAllParts(game.Workspace, BrickColor.Red())

Wouldn’t this run endlessly?

And

How does the loop know when to stop?

1 Like

You’re looping through objects once, it won’t run endlessly.

I just realized that you’re recalling the function in itself. Yes, it will run endlessly.

It doesn’t unless it gets exhausted or you stop it manually.

1 Like

wouldnt the function check all of the descendants in the workspace and then end

1 Like

No because you are calling the function again.

And plus, you are calling the function for every children of workspace. Then each children will call the function for every children, then each children to other children, then the cycle keeps going on and on.

1 Like

yes but youre calling the function again for all the children in a given object so it will have to have no children left to check at some point and when that point is reached the loop will just stop running

2 Likes

Oh right, well then yes it will keep looping until all descendants have been colored (then it will stop).

1 Like

Recursion is when a function calls itself

local function n(i)
  print(i)
  return n(i + 1)
end

n(1)
1
2
3
4
...

Recursion is useful, for example, if you want to navigate a tree of unknown depth.

2 Likes