usertypes.hpp 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. /* Luwra
  2. * Minimal-overhead Lua wrapper for C++
  3. *
  4. * Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
  5. */
  6. #ifndef LUWRA_USERTYPES_H_
  7. #define LUWRA_USERTYPES_H_
  8. #include "common.hpp"
  9. #include "types.hpp"
  10. #include "stack.hpp"
  11. #include "functions.hpp"
  12. #include <utility>
  13. #include <atomic>
  14. #include <cassert>
  15. LUWRA_NS_BEGIN
  16. namespace internal {
  17. static
  18. std::atomic_size_t UserTypeCounter;
  19. template <typename T>
  20. std::string UserTypeName = "";
  21. template <typename T, typename... A>
  22. int UserTypeConstructor(State* state) {
  23. return Apply(state, std::function<int(A...)>([state](A... args) {
  24. return Value<T&>::Push(state, args...);
  25. }));
  26. }
  27. template <typename T>
  28. int UserTypeDestructor(State* state) {
  29. Value<T&>::Read(state, 1).~T();
  30. return 0;
  31. }
  32. template <typename T>
  33. int UserTypeToString(State* state) {
  34. return Value<std::string>::Push(
  35. state,
  36. internal::UserTypeName<T>
  37. );
  38. }
  39. template <typename T, typename S>
  40. struct MethodWrapper {
  41. static_assert(
  42. sizeof(T) == -1,
  43. "The MethodWrapper template expects a type name and a function signature as parameter"
  44. );
  45. };
  46. template <typename T, typename R, typename... A>
  47. struct MethodWrapper<T, R(A...)> {
  48. using MethodPointerType = R (T::*)(A...);
  49. using FunctionSignature = R (T&, A...);
  50. template <MethodPointerType MethodPointer> static
  51. R delegate(T& parent, A... args) {
  52. return (parent.*MethodPointer)(std::forward<A>(args)...);
  53. }
  54. };
  55. }
  56. /**
  57. * Instances of user types shall always be used as references, because Lua values can not be
  58. * referenced, hence this allows the compiler to differentiate between them.
  59. * The life-time of such instance is determined by Lua.
  60. */
  61. template <typename T>
  62. struct Value<T&> {
  63. static inline
  64. T& Read(State* state, int n) {
  65. assert(!internal::UserTypeName<T>.empty());
  66. return *static_cast<T*>(
  67. luaL_checkudata(state, n, internal::UserTypeName<T>.c_str())
  68. );
  69. }
  70. template <typename... A> static inline
  71. int Push(State* state, A&&... args) {
  72. assert(!internal::UserTypeName<T>.empty());
  73. void* mem = lua_newuserdata(state, sizeof(T));
  74. if (!mem) {
  75. luaL_error(state, "Failed to allocate user type");
  76. return -1;
  77. }
  78. // Call constructor on instance
  79. new (mem) T(std::forward<A>(args)...);
  80. // Set metatable for this type
  81. luaL_getmetatable(state, internal::UserTypeName<T>.c_str());
  82. lua_setmetatable(state, -2);
  83. return 1;
  84. }
  85. };
  86. /**
  87. * Register the metatable for the user type `T`. This function allows you to register methods
  88. * which are shared across all instances of this type. A garbage-collector hook is also inserted;
  89. * it destructs the underlying type when the garbage-collector says it is time to say good-bye.
  90. */
  91. template <typename T> static inline
  92. void RegisterUserType(
  93. State* state,
  94. std::initializer_list<std::pair<const char*, CFunction>> methods,
  95. std::initializer_list<std::pair<const char*, CFunction>> meta_methods = {}
  96. ) {
  97. // Setup an appropriate meta table name
  98. if (internal::UserTypeName<T>.empty())
  99. internal::UserTypeName<T> = "UD#" + std::to_string(internal::UserTypeCounter++);
  100. luaL_newmetatable(state, internal::UserTypeName<T>.c_str());
  101. // Register methods
  102. lua_pushstring(state, "__index");
  103. lua_newtable(state);
  104. for (auto& method: methods) {
  105. lua_pushstring(state, method.first);
  106. lua_pushcfunction(state, method.second);
  107. lua_rawset(state, -3);
  108. }
  109. lua_rawset(state, -3);
  110. // Register garbage-collection hook
  111. lua_pushstring(state, "__gc");
  112. lua_pushcfunction(state, &internal::UserTypeDestructor<T>);
  113. lua_rawset(state, -3);
  114. // Register string representation function
  115. lua_pushstring(state, "__tostring");
  116. lua_pushcfunction(state, &internal::UserTypeToString<T>);
  117. lua_rawset(state, -3);
  118. // Insert meta methods
  119. for (auto& metamethod: meta_methods) {
  120. lua_pushstring(state, metamethod.first);
  121. lua_pushcfunction(state, metamethod.second);
  122. lua_rawset(state, -3);
  123. }
  124. // Pop meta table off the stack
  125. lua_pop(state, -1);
  126. }
  127. /**
  128. * Constructor function for a type `T`. Variadic arguments must be used to specify which parameters
  129. * to use during construction.
  130. */
  131. template <typename T, typename... A>
  132. constexpr CFunction WrapConstructor = &internal::UserTypeConstructor<T, A...>;
  133. /**
  134. * Works similiar to `WrapFunction`. Given a class or struct declaration as follows:
  135. *
  136. * struct T {
  137. * R my_method(A0, A1 ... An);
  138. * };
  139. *
  140. * You might wrap this method easily:
  141. *
  142. * CFunction wrapped_meth = WrapMethod<T, R(A0, A1 ... An), &T::my_method>;
  143. *
  144. * In Lua, assuming `instance` is a userdata instance of type `T`, x0, x1 ... xn are instances
  145. * of A0, A1 ... An, and the method has been bound as `my_method`; it is possible to invoke the
  146. * method like so:
  147. *
  148. * instance:my_method(x0, x1 ... xn)
  149. */
  150. template <
  151. typename T,
  152. typename S,
  153. typename internal::MethodWrapper<T, S>::MethodPointerType MethodPointer
  154. >
  155. constexpr CFunction WrapMethod =
  156. WrapFunction<
  157. typename internal::MethodWrapper<T, S>::FunctionSignature,
  158. internal::MethodWrapper<T, S>::template delegate<MethodPointer>
  159. >;
  160. LUWRA_NS_END
  161. #endif