stack overflow on recursive function. Not sure how to fix.

For some reason the code below throws a stack overflow error if the else statement gets executed too many times. I am trying to have the scene.targeting function select a target from the objTable passed in the params, but only targets with a .tgtFlag == false are valid selections. If the function selects a target that has a .tgtFlag == true, it recalls the scene.targeting function passing in the same set of params.

The line that breaks is “local theTarget = params.objTable[math.random( 1, #params.objTable )]” but only after “else scene.targeting(params) end” is called several times.

Any help would be greatly appreciated.

function scene.targeting( params ) -- Targeting functions function animateTarget( target ) if target.savedFlag == false then transition.to( target, {time = 100, y = target.y - 15} ) transition.to( target, {time = 100, delay = 150, y = target.y, onComplete = animateTarget} ) end end -- something is broken on line 79 or line 84. Getting a stack overflow whene else statement gets executed repeatedly. local theTarget = params.objTable[math.random( 1, #params.objTable )] if theTarget.tgtFlag == false then theTarget.tgtFlag = true animateTarget(theTarget) else scene.targeting(params) end end

try return scene.targeting(params) instead. 

http://www.lua.org/pil/6.3.html

Thanks. Didn’t know about tail calls. Thats a handy trick.

try return scene.targeting(params) instead. 

http://www.lua.org/pil/6.3.html

Thanks. Didn’t know about tail calls. Thats a handy trick.