title: Using Lua to define NPC behaviour in a C++ game engine
body: <p>I'm working on a game engine in C++ using Lua for NPC behaviour. I ran into some problems during the design.</p>
  
  <p>For everything that needs more than one frame for execution I wanted to use a linked list of processes (which are C++ classes). So this:</p>
  
  <pre><code>goto(point_a)
  say("Oh dear, this lawn looks really scruffy!")
  mowLawn()
  </code></pre>
  
  <p>would create a GotoProcess object, which would have a pointer to a SayProcess object, which would have a pointer to a MowLawnProcess object. These objects would be created instantly when the NPC is spawned, no further scripting needed.
  The first of these objects will be updated each frame. When it's finished, it will be deleted and the next one will be used for updating.
  I extended this model by a ParallelProcess which would contain multiple processes that are updated simultaneously.</p>
  
  <p>I found some serious problems. Look at this example: I want a character to walk to point_a and then go berserk and just attack anybody who comes near. The script would look like that:</p>
  
  <pre><code>goto(point_a)
  while true do
      character = getNearestCharacterId()
      attack(character)
  end
  </code></pre>
  
  <p>That wouldn't work at all with my design. First of all, the character variable would be set at the beginning, when the character hasn't even started walking to point_a. Then, then script would continue adding AttackProcesses forever due to the while loop.</p>
  
  <p>I could implement a WhileProcess for the loop and evaluate the script line by line. I doubt this would increase readability of the code though.</p>
  
  <p>Is there another common approach I didn't think of to tackle this problem?</p>