From 8af9fa830e4a27c28c78ee2d3d0bb778fd14054a Mon Sep 17 00:00:00 2001
From: Allanis <allanis@saracraft.net>
Date: Sun, 18 May 2014 21:43:51 +0100
Subject: [PATCH] [Fix] Fix the occasional AI warnings.

---
 scripts/ai/include/attack_generic.lua | 20 ++++++++++++++------
 scripts/ai/tpl/generic.lua            |  9 ++++++++-
 2 files changed, 22 insertions(+), 7 deletions(-)

diff --git a/scripts/ai/include/attack_generic.lua b/scripts/ai/include/attack_generic.lua
index 7294035..e962948 100644
--- a/scripts/ai/include/attack_generic.lua
+++ b/scripts/ai/include/attack_generic.lua
@@ -13,9 +13,15 @@ function atk_g_think()
   enemy = ai.getenemy()
   target = ai.target()
 
+  -- Stop attacking if it doesn't exist.
+  if not ai.exists(target) then
+    ai.poptask()
+    return
+  end
+
   -- Get new target if it's closer.
   if enemy ~= target and enemy ~= nil then
-    dist = ai.dist(ai.pos(target))
+    dist = ai.dist(target)
     range = ai.getweaprange()
 
     -- Shouldn't switch targets if close.
@@ -32,19 +38,21 @@ end
 function atk_g()
   target = ai.target()
 
+  -- Make sure pilot exists.
+  if not ai.exists(target) then
+    ai.poptask()
+    return
+  end
+
   -- Check if is bribed by target.
   if ai.isbribed(target) then
     ai.poptask()
     return
   end
 
+  -- Targetting stuff.
   ai.hostile(target) -- Mark as hostile.
 
-  -- Make sure pilot exists.
-  if not ai.exists(target) then
-    ai.poptask()
-    return
-  end
   ai.settarget(target)
 
   -- Get stats about enemy.
diff --git a/scripts/ai/tpl/generic.lua b/scripts/ai/tpl/generic.lua
index 3790211..5d622bd 100644
--- a/scripts/ai/tpl/generic.lua
+++ b/scripts/ai/tpl/generic.lua
@@ -34,6 +34,12 @@ function control()
   -- Think for attacking.
   elseif task == "attack" then
     target = ai.target()
+
+    -- Needs to have a target.
+    if target == nil then
+      ai.poptask()
+    end
+
     -- Runaway if needed.
     if(shield_run > 0 and ai.pshield() < shield_run
       and ai.pshield() < ai.pshield(target)) or
@@ -48,7 +54,8 @@ function control()
 
   -- Pilot is running away.
   elseif task == "runaway" then
-    dist = ai.dist(ai.pos(ai.target()))
+    target = ai.target()
+    dist = ai.dist(target)
 
     if aggressive and((shield_return > 0 and ai.pshield() >= shield_return) or
         (armour_return > 0 and ai.parmour() >= armour_return)) then