Why recursion is used in scripts?

Hi Guys, so basically I saw some scripts in which the function calls itself inside the function. It’s called recursion. But I wonder why is it even used ? What’s the use of it ? Thanks :slight_smile:

1 Like

Personally, the only time I use recursion is whenever for example a call to an api of mine fails so I automatically restart it.

For example, lets say im sending a request to example.com and the request fails. Instead of just returning nil, I instead recall the function to re-request the data from example.com Recursion isn’t something that I personally use a lot. Nor would I recommend it as it may cause lag. Although it may have use for stuff like HTTP requests.

2 Likes

Recursion can be useful for considering all possibilities. For example, it can be useful in some cases for NPC loops that need to be active. Consider the following:

local NPC = {}

function NPC.new()
	local Info = setmetatable({}, {__index = NPC})
	Info.Number = math.random(1, 100)
	
	Info:Attack()
end

function NPC:MoveTo()

end

--Leads to attacking in all cases
function NPC:Idle()
	
	local Near = false
	
	repeat
		--Probably have a loop here detecting nearby players
	until Near == true
	
	self:Attack()
	
end

--Leads to idling in all cases
function NPC:Attack(Target)
	
	local Distance = 10 --Would normally be a measurement between two vectors
	local Limit = 5
	
	if Distance > Limit then
		self:Idle()
	else
		--Attack then idle
		self:Idle()
	end
	
end

return NPC

You have two functions that will most likely be used a lot, so it’s very convenient to call them within each others functions.

While it is useful in cases like these, I do highly recommend not to have recursions going deeper than a couple layers. Something like what I’ve created here could run forever without being stopped.

1 Like

Recursion has many use cases, the only one I can really think of in the spot is something like searching nested dictionaries that have an unknown depth:

function searchNestedDicts(dict, targetKey, targetVal)
    for key, value in dict do
        if key == targetKey and value == targetVal then
            return dict
        end
        if typeof(value) == table then
            searchNestedDicts(value, targetKey, targetValue)
        end
    end
end

This isn’t tested and was written on mobile but the concept should get through even if it’s not working as intended, also if table is not the type of a dict remind me what I was supposed to put there

2 Likes