Recursion is a form of looping, where a
Articles/Understanding Functions in Roblox|function calls itself, usually until a condition is met. Although recursion can be somewhat difficult to understand at first, it can result in much cleaner code.
One of the most common examples of recursion is an implementation of the factorial function. The code below has two sections: the base step, and the recursive step. Keep in mind that if you do not have a base step, and only a recursive step, your function will recurse endlessly, causing the stack to overflow.
The base step simply returns a value of one when n is one or zero.
Since we know that the factorial of 1 equals 1, we know that the factorial of two equals two times the factorial of one. In code,
factorial(2) == 2*factorial(1) = 2*1 = 2
It follows that the factorial of three is three times the factorial of two. In code,
factorial(3) == 3*factorial(2) = 3*2*factorial(1) = 3*2*1 = 6
Generalizing, the factorial of n is n times the factorial of n-1. In code,
factorial(n) = n*factorial(n-1)
The following code is for the factorial function:
function factorial(n) if n <= 1 then -- base case return 1 else return n * factorial(n-1) -- recursive step end end print(factorial(5))
Usage in Roblox
Inside of games, recursion can be used for several things. A basic example would be searching through
Workspace to find all of a given class (parts, models, etc.) and then doing something with them. Recursion allows you to use the function again in order to search through models, tools, etc, in case the object you are looking for is not a direct descendant. The following example attempts to find all of the parts in
Workspace, and then colors them red.
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())