diff options
author | Thorbjørn Lindeijer <thorbjorn@lindeijer.nl> | 2012-03-09 21:30:42 +0100 |
---|---|---|
committer | Thorbjørn Lindeijer <thorbjorn@lindeijer.nl> | 2012-03-10 18:07:29 +0100 |
commit | 78c912fb4007c3e5f0b43de02646772acb21ecf2 (patch) | |
tree | e45409ff061de75b0e4273763a87f5a25de6a65b /src/scripting/script.cpp | |
parent | 2fa7d1f39b24714ee6dc72b6b9e61ec5a1997724 (diff) | |
download | manaserv-78c912fb4007c3e5f0b43de02646772acb21ecf2.tar.gz manaserv-78c912fb4007c3e5f0b43de02646772acb21ecf2.tar.bz2 manaserv-78c912fb4007c3e5f0b43de02646772acb21ecf2.tar.xz manaserv-78c912fb4007c3e5f0b43de02646772acb21ecf2.zip |
Moved the managing of NPC script coroutines into C++
Rather than wrapping NPC functions up in coroutines in the Lua side, they
are now managed on the C++ side as "script threads", which are essentially
the same thing.
The main purpose is that the server can now know whether any of these long
running script interactions are still active, which will probably be useful
when adding the ability to reload scripts.
Reviewed-by: Erik Schilling
Diffstat (limited to 'src/scripting/script.cpp')
-rw-r--r-- | src/scripting/script.cpp | 42 |
1 files changed, 41 insertions, 1 deletions
diff --git a/src/scripting/script.cpp b/src/scripting/script.cpp index 9ef069d5..6312d1ce 100644 --- a/src/scripting/script.cpp +++ b/src/scripting/script.cpp @@ -25,6 +25,7 @@ #include "game-server/being.h" #include "utils/logger.h" +#include <cassert> #include <cstdlib> #include <map> @@ -38,10 +39,17 @@ Script::Ref Script::mCreateNpcDelayedCallback; Script::Ref Script::mUpdateCallback; Script::Script(): - mMap(NULL), + mCurrentThread(0), + mMap(0), mEventListener(&scriptEventDispatch) {} +Script::~Script() +{ + // There should be no remaining threads when the Script gets deleted + assert(mThreads.empty()); +} + void Script::registerEngine(const std::string &name, Factory f) { if (!engines) @@ -120,3 +128,35 @@ void Script::loadNPC(const std::string &name, int id, int x, int y, push(y); execute(); } + + +/** + * Removes one element matching the given value by overwriting it with the last + * element and then popping the last element. + */ +template<typename T> +static void fastRemoveOne(std::vector<T> &vector, T value) +{ + for (size_t i = vector.size() - 1; i >= 0; --i) + { + if (vector.at(i) == value) + { + vector.at(i) = vector.back(); + vector.pop_back(); + break; + } + } +} + +Script::Thread::Thread(Script *script) : + mScript(script), + mState(ThreadPending), + mMap(0) +{ + script->mThreads.push_back(this); +} + +Script::Thread::~Thread() +{ + fastRemoveOne(mScript->mThreads, this); +} |