# Why does this recursion keep freezing/crashing?

``````function setup()
local cp_tree1 = Coprime( 2, 1, 1, nil )
cp_tree1:generateBranchesUntilDepth( 2 ) --works fine
cp_tree1:generateBranchesUntilDepth( 3 ) -- freezes Codea

end

Coprime = class()

function Coprime:init(a,b, depth, p)
print ("Coprime:init(depth="..depth..","..a..","..b..")" )
self.m = a
self.n = b
self.b1 = nil
self.b2 = nil
self.b3 = nil
self.parent = p or nil
self.branchDepth = depth or 0
end

function Coprime:calcBranch( )
local s = self
local m = s.m
local n = s.n
local d = s.branchDepth+1
s.b1 = Coprime(2*m-n, m, d, s)
s.b2 = Coprime(2*m+n, m, d, s )
s.b3 = Coprime(m+2*n, n, d, s )
return s.b1, s.b2, s.b3
end

function Coprime:generateBranchesUntilDepth( n )
local s = self
--local m = s.m
--local n = s.n
print(n, "generateBranchesUntilDepth() for cp("..s.m..","..s.n..")" )
--local d = s.branchDepth+1
local b1 = nil
local b2 = nil
local b3 = nil

b1, b2, b3 = s:calcBranch()
while( b1.branchDepth < n ) do
b1:generateBranchesUntilDepth( n ) --why does this recursion crash?
end
--[[
while( b2.branchDepth < n ) do
b2:generateBranchesUntilDepth( n )
end
while( b3.branchDepth < n ) do
b3:generateBranchesUntilDepth( n )
end
]]--
end
``````

your while loop never updates b1.branchDepth so you have forever b1.branchDepth < n true.

look at how i modified your code to get out the infinite loop, with an nmax control variable. This helps to understand what is going wrong

``````function setup()
local cp_tree1 = Coprime( 2, 1, 1, nil )
cp_tree1:generateBranchesUntilDepth( 2 ) --works fine
cp_tree1:generateBranchesUntilDepth( 3 ) -- freezes Codea

end

Coprime = class()
nmax = 0
function Coprime:init(a,b, depth, p)
nmax = nmax + 1
print (tostring(nmax).." Coprime:init(depth="..depth..","..a..","..b..")" )
self.m = a
self.n = b
self.b1 = nil
self.b2 = nil
self.b3 = nil
self.parent = p or nil
self.branchDepth = depth or 0
end

function Coprime:calcBranch( )
local s = self
local m = s.m
local n = s.n
local d = s.branchDepth+1
s.b1 = Coprime(2*m-n, m, d, s)
s.b2 = Coprime(2*m+n, m, d, s )
s.b3 = Coprime(m+2*n, n, d, s )
return s.b1, s.b2, s.b3
end

function Coprime:generateBranchesUntilDepth( n )
local s = self
--local m = s.m
--local n = s.n
print(n, "generateBranchesUntilDepth() for cp("..s.m..","..s.n..")" )
--local d = s.branchDepth+1
local b1 = nil
local b2 = nil
local b3 = nil

b1, b2, b3 = s:calcBranch()
while( b1.branchDepth < n and nmax<20) do
b1:generateBranchesUntilDepth( n ) --why does this recursion crash?
end
--[[
while( b2.branchDepth < n ) do
b2:generateBranchesUntilDepth( n )
end
while( b3.branchDepth < n ) do
b3:generateBranchesUntilDepth( n )
end
]]--
end
``````

as soon as I switched the while() to an if(), it worked

you’re welcome…