From 9890cbf428b6216b05de02805c77c45d7b0983ab Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Sun, 21 Feb 2021 23:46:37 -0500 Subject: Multiple scripts can be run at once And they're all on their own threads again. This is mostly so debug commands can be run during execution of other scripts. But it can also be useful for map init scripts (if we want a script to run whenever a map is loaded, even though map loading is usually done by a script). --- src/script_system.cpp | 38 +++++++++++++++++++++----------------- 1 file changed, 21 insertions(+), 17 deletions(-) (limited to 'src/script_system.cpp') diff --git a/src/script_system.cpp b/src/script_system.cpp index fcc7ab5..c7c3938 100644 --- a/src/script_system.cpp +++ b/src/script_system.cpp @@ -192,17 +192,17 @@ ScriptSystem::ScriptSystem(Game& game) : game_(game) { void ScriptSystem::tick(double dt) { if (game_.isGameplayPaused()) return; - if (callable_ && *callable_) { - auto result = (*callable_)(dt); + for (Script& script : scripts_) { + auto result = (*script.callable)(dt); if (!result.valid()) { sol::error e = result; throw e; } - - if (!*callable_) { - callable_.reset(); - } } + + scripts_.remove_if([] (const Script& script) { + return (!*script.callable); + }); } void ScriptSystem::runScript(std::string mapName, std::string scriptName) { @@ -211,41 +211,45 @@ void ScriptSystem::runScript(std::string mapName, std::string scriptName) { loadedScripts_.insert(mapName); } - callable_.reset(new sol::coroutine(engine_.traverse_get(mapName, scriptName))); + Script newScript; + newScript.runner.reset(new sol::thread(sol::thread::create(engine_.lua_state()))); + newScript.callable.reset(new sol::coroutine(engine_.traverse_get(mapName, scriptName))); - if (!*callable_) { + if (!*newScript.callable) { throw std::runtime_error("Error running script: " + mapName + "." + scriptName); } - auto result = (*callable_)(); + auto result = (*newScript.callable)(); if (!result.valid()) { sol::error e = result; throw e; } - if (!*callable_) { - callable_.reset(); + if (*newScript.callable) { + scripts_.push_back(std::move(newScript)); } } void ScriptSystem::runDebugScript(std::string script) { - sol::load_result loaded_script = engine_.load(script); + Script newScript; + newScript.runner.reset(new sol::thread(sol::thread::create(engine_.lua_state()))); - callable_.reset(new sol::coroutine(loaded_script)); + sol::load_result loaded_script = newScript.runner->state().load(script); + newScript.callable.reset(new sol::coroutine(loaded_script)); - if (!*callable_) { + if (!*newScript.callable) { std::cout << "Error running debug command: " << script << std::endl; return; } - auto result = (*callable_)(); + auto result = (*newScript.callable)(); if (!result.valid()) { sol::error e = result; std::cout << e.what() << std::endl; return; } - if (!*callable_) { - callable_.reset(); + if (*newScript.callable) { + scripts_.push_back(std::move(newScript)); } } -- cgit 1.4.1