Nextbot & Coroutines
Thursday, March 28, 2013
I've made a bit of progress binding the Nextbot stuff.. despite not talking about it.
When I was designing how it should interface with Lua I started off mimicing how it worked in the engine. After a few good sleeps I decided that it wasn't the way to go. It's coded like that in the engine because of the limitations of C++. We don't have these limitations in Lua – so lets try to use that to our advantage.
So I decided to use coroutines. First of all let me get this out of the way. Coroutines aren't threads. They don't really offer any speed benefits. A more accurate way to imagine them is as a function that you can pause and resume at any time. So imagine you're writing a script that prints text.. you could do something like this.
So where before you would use timers or whatever to achieve this.. your code is instantly a lot simpler to follow.
This is good for a lot of stuff in AI because a lot of the actions happen in a timed order. You do one thing, then you do another, then another.
Here's one I made earlier. This guy is very simple. He tries to walk somewhere. Then he sits down. Then he gets up and tries to run to a good hiding place. The code is just as simple.
Obviously I don't expect people will code their AI in one function, but this gives you an idea of the simplicity of this. I imagine in reality you'll have functions like TryToFindPlayer(), AttackPlayer() and Flee(). Or more realistically a single function called ThrowMonitorAtPlayer().