timer.performWithDelay not firing properly

Hello I have been having this timer firing problem for a few days now that I cant seem to figure out. I am trying to get the timer to only activate a certain amount of times or infinite but infinite gives it even more weird results. That code should get the monster to attack 50 times but usually it stops like around 17 or 20 and starts to get weird results earlier, I tried several different methods and lots of times it will double fire doing it through different ways… I also tried to move to different timers and cancel old ones but that still gave weird effects.

What the code does is create a seperate square physics body around the monster that is after deleted milliseconds after the attack and recontinues till monster is dead, was my of thinking on how to do battle, not too sure if this is the right approach. I just want the timer to fire properly and not do double fire or perform weird.

[lua]local function cleanMonsterAttack1 ( event, monster )
   if event.isBodyActive == true and monster ~= nil then
      monster:setSequence(“passive”)
      monster:play()
      physics.removeBody( event)
      mte.removeSprite(event, false)
      event = nil
      monsterAttackUsed = false
      return true
   elseif event.isBodyActive == true and monster == nil then
      physics.removeBody( event)
      mte.removeSprite(event, false)
      event = nil
      return true
   end
end


–Monster attack


local function monsterAttack1 ( event )
if event ~= nil then
    event:setSequence(“alert”)
   event:play()
   downSwordSetup.layer = player.layer - 1
   downSwordSetup.locX = event.locX
   downSwordSetup.locY = event.locY
   monsterAttack.isVisible = false
   mte.addSprite(monsterAttack, downSwordSetup)
   if (player.level <= 2) then
       physics.addBody( monsterAttack, “static”, { density=0, friction=0, bounce=0, isSensor = true, filter = { categoryBits = player.level, maskBits = player.level }, shape = monsterAttackShape} )
end
   monsterAttack.type = “monsterAttack”
   if timer2 == nil then
       timer2 = timer.performWithDelay( 500, function() cleanMonsterAttack1(monsterAttack, event); end, 50 )
   end
   return true
   else
      return false
   end
end


– Player Collision

local function onCollision(event)
if event.phase == “began” then
local agro = event.object1
local hit = event.object2

if (agro.type == “player” and hit.type == “NPC_2”) or
(agro.type == “NPC_2” and hit.type == “player”)then
    if NPC_2 ~= nil then
        if timer1 == nil then
            timer1 = timer.performWithDelay( 1500, function() monsterAttack1(NPC_2); end, 50 )
        end
–monsterAttackUsed = true
    end

end

[/lua]

Please help would be greatly appreciated, still bashed my head against this for another day :frowning: just would like the timers to work properly

Please help would be greatly appreciated, still bashed my head against this for another day :frowning: just would like the timers to work properly