Search code examples
luacoronasdk

Lua stack overflow in recursive function in corona sdk


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

  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

Solution

  • Referring to Programming in Lua:

    A tail call is a kind of goto dressed as a call. A tail call happens when a function calls another as its last action, so it has nothing else to do.

    In your example, animateTarget obviously isn't called in such a way, and can and will suffer from stack overflows. Either rewrite it to make use of TCO or change it to non-recursive version.