Advertisement
eliasdaler

InputCallback

Jan 29th, 2017
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. // InputCallback.h
  2. #pragma once
  3.  
  4. #include <functional>
  5. #include <sol.hpp>
  6.  
  7. template <typename... Args>
  8. class InputCallback {
  9.     using CppCallbackFunction_t = std::function<void(Args...)>;
  10.  
  11.     template <typename CallerType>
  12.     using CppMemberCallbackFunction_t = void (CallerType::*)(Args...);
  13.  
  14.     enum class Type {
  15.         Cpp,
  16.         Lua
  17.     };
  18. public:
  19.     InputCallback();
  20.  
  21.     template <typename CallerType>
  22.     void setCallback(CallerType* const caller, CppMemberCallbackFunction_t<CallerType> f);
  23.  
  24.     void setCallback(sol::object c, sol::protected_function f);
  25.  
  26.     template <typename... FArgs>
  27.     void call(FArgs&&... args);
  28. private:
  29.     Type type;
  30.     sol::protected_function luaCallback;
  31.     sol::object caller;
  32.     CppCallbackFunction_t cppCallback;
  33. };
  34.  
  35. #include "InputCallback.inl"
  36.  
  37. // InputCallback.inl
  38.  
  39. #pragma once
  40.  
  41. template <typename... Args>
  42. InputCallback<Args...>::InputCallback() :
  43.     type(Type::Cpp)
  44. {}
  45.  
  46. template <typename... Args>
  47. template <typename CallerType>
  48. void InputCallback<Args...>::setCallback(CallerType* const caller, CppMemberCallbackFunction_t<CallerType> f)
  49. {
  50.     type = Type::Cpp;
  51.     cppCallback = [caller, f](Args... args) { (caller->*f)(std::forward<Args>(args)...); };
  52. }
  53.  
  54. template <typename... Args>
  55. void InputCallback<Args...>::setCallback(sol::object c, sol::protected_function f)
  56. {
  57.     type = Type::Lua;
  58.     caller = c;
  59.     luaCallback = f;
  60. }
  61.  
  62. #include <System/EngineSystem.h>
  63. #include <System/Managers/LogManager.h>
  64.  
  65. template <typename... Args>
  66. template <typename... FArgs>
  67. void InputCallback<Args...>::call(FArgs&&... args)
  68. {
  69.     switch (type) {
  70.     case Type::Cpp:
  71.         cppCallback(std::forward<FArgs>(args)...);
  72.         break;
  73.     case Type::Lua:
  74.         sol::protected_function_result r =
  75.             luaCallback(caller, std::forward<FArgs>(args)...);
  76.         if (!r.valid()) {
  77.             sol::error e = r;
  78.             auto& log = engine_system.get<LogManager>();
  79.             log(LogManager::MessageType::Lua_Exception) << e.what();
  80.         }
  81.         break;
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement