diff options
author | LaG1924 <12997935+LaG1924@users.noreply.github.com> | 2019-02-17 17:24:52 +0100 |
---|---|---|
committer | LaG1924 <12997935+LaG1924@users.noreply.github.com> | 2019-04-21 12:55:48 +0200 |
commit | a2fd708de4ede7427589125e680f3fb339926f4e (patch) | |
tree | 75faed7c12a7898e435cf9f40e1ca3af85ca06ec /src/Plugin.cpp | |
parent | Minor lua-api improvement (diff) | |
download | AltCraft-a2fd708de4ede7427589125e680f3fb339926f4e.tar AltCraft-a2fd708de4ede7427589125e680f3fb339926f4e.tar.gz AltCraft-a2fd708de4ede7427589125e680f3fb339926f4e.tar.bz2 AltCraft-a2fd708de4ede7427589125e680f3fb339926f4e.tar.lz AltCraft-a2fd708de4ede7427589125e680f3fb339926f4e.tar.xz AltCraft-a2fd708de4ede7427589125e680f3fb339926f4e.tar.zst AltCraft-a2fd708de4ede7427589125e680f3fb339926f4e.zip |
Diffstat (limited to '')
-rw-r--r-- | src/Plugin.cpp | 81 |
1 files changed, 81 insertions, 0 deletions
diff --git a/src/Plugin.cpp b/src/Plugin.cpp new file mode 100644 index 0000000..40ff82f --- /dev/null +++ b/src/Plugin.cpp @@ -0,0 +1,81 @@ +#include "Plugin.hpp" + +#include <vector> + +#include <easylogging++.h> +#include <sol.hpp> + +struct Plugin { + const std::string name; + const std::string displayName; + const std::function<void()> onLoad; + const std::function<void()> onUnload; + const std::function<void(std::string)> onChangeState; +}; + + +std::vector<Plugin> plugins; +sol::state lua; + + +namespace PluginApi { + + void RegisterPlugin(sol::table &self, sol::table &plugin) { + Plugin nativePlugin { + plugin["name"].get_or<std::string>("75"), + plugin["displayName"].get_or<std::string>(""), + plugin["onLoad"].get_or(std::function<void()>()), + plugin["onUnload"].get_or(std::function<void()>()), + plugin["onChangeState"].get_or(std::function<void(std::string)>()) + }; + plugins.push_back(nativePlugin); + nativePlugin.onLoad(); + + LOG(INFO) << "Loaded plugin " << (!nativePlugin.displayName.empty() ? nativePlugin.displayName : nativePlugin.name); + } + + void LogWarning(sol::table &self, std::string text) { + LOG(WARNING) << text; + } + +} + +void PluginSystem::Init() +{ + LOG(INFO) << "Initializing plugin system"; + for (Plugin &plugin : plugins) { + if (plugin.onUnload) + plugin.onUnload(); + } + + plugins.clear(); + lua = sol::state(); + lua.open_libraries(); + + sol::table apiTable = lua["AC"].get_or_create<sol::table>(); + + apiTable["RegisterPlugin"] = PluginApi::RegisterPlugin; + apiTable["LogWarning"] = PluginApi::LogWarning; +} + +void PluginSystem::Execute(const std::string &luaCode) +{ + try { + lua.safe_script(luaCode); + } catch (sol::error &e) { + LOG(ERROR) << e.what(); + } +} + +void PluginSystem::CallOnChangeState(std::string newState) +{ + for (Plugin &plugin : plugins) { + if (plugin.onChangeState) + try { + plugin.onChangeState(newState); + } + catch (sol::error &e) { + LOG(ERROR) << e.what(); + } + } +} |