usertypes.hpp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 <map>
  13. #include <utility>
  14. #include <atomic>
  15. #include <cassert>
  16. LUWRA_NS_BEGIN
  17. namespace internal {
  18. static
  19. std::atomic_size_t user_type_counter;
  20. template <typename T>
  21. std::string user_type_name = "";
  22. template <typename T, typename... A>
  23. int construct_user_type(State* state) {
  24. return internal::Layout<int(A...)>::direct(
  25. state,
  26. 1,
  27. &Value<T&>::template push<A...>,
  28. state
  29. );
  30. }
  31. template <typename T>
  32. int destruct_user_type(State* state) {
  33. if (!lua_islightuserdata(state, 1))
  34. Value<T&>::read(state, 1).~T();
  35. return 0;
  36. }
  37. template <typename T>
  38. int stringify_user_type(State* state) {
  39. return push(state, internal::user_type_name<T>);
  40. }
  41. template <typename T, typename R, R T::* property_pointer>
  42. int access_user_type_property(State* state) {
  43. if (lua_gettop(state) > 1) {
  44. // Setter
  45. (Value<T&>::read(state, 1).*property_pointer) = Value<R>::read(state, 2);
  46. return 0;
  47. } else {
  48. // Getter
  49. return push(state, Value<T&>::read(state, 1).*property_pointer);
  50. }
  51. }
  52. template <typename T, typename S>
  53. struct MethodWrapper {
  54. static_assert(
  55. sizeof(T) == -1,
  56. "The MethodWrapper template expects a type name and a function signature as parameter"
  57. );
  58. };
  59. template <typename T, typename R, typename... A>
  60. struct MethodWrapper<T, R(A...)> {
  61. using MethodPointerType = R (T::*)(A...);
  62. using FunctionSignature = R (T&, A...);
  63. template <MethodPointerType method_pointer> static
  64. R delegate(T& parent, A... args) {
  65. return (parent.*method_pointer)(std::forward<A>(args)...);
  66. }
  67. };
  68. }
  69. /**
  70. * User type T.
  71. * Instances created using this specialization are allocated and constructed as full user data
  72. * types in Lua. The default garbage-collecting hook will destruct the user type, once it has
  73. * been marked.
  74. */
  75. template <typename T>
  76. struct Value<T&> {
  77. static inline
  78. T& read(State* state, int n) {
  79. assert(!internal::user_type_name<T>.empty());
  80. return *static_cast<T*>(
  81. luaL_checkudata(state, n, internal::user_type_name<T>.c_str())
  82. );
  83. }
  84. template <typename... A> static inline
  85. int push(State* state, A&&... args) {
  86. assert(!internal::user_type_name<T>.empty());
  87. void* mem = lua_newuserdata(state, sizeof(T));
  88. if (!mem) {
  89. luaL_error(state, "Failed to allocate user type");
  90. return -1;
  91. }
  92. // Call constructor on instance
  93. new (mem) T(std::forward<A>(args)...);
  94. // Set metatable for this type
  95. luaL_getmetatable(state, internal::user_type_name<T>.c_str());
  96. lua_setmetatable(state, -2);
  97. return 1;
  98. }
  99. };
  100. /**
  101. * User type T.
  102. * Instances created using this specialization are allocated as light user data in Lua.
  103. * The default garbage-collector does not destruct light user data types.
  104. */
  105. template <typename T>
  106. struct Value<T*> {
  107. static inline
  108. T* read(State* state, int n) {
  109. assert(!internal::user_type_name<T>.empty());
  110. return static_cast<T*>(
  111. luaL_checkudata(state, n, internal::user_type_name<T>.c_str())
  112. );
  113. }
  114. static inline
  115. int push(State* state, T* instance) {
  116. assert(!internal::user_type_name<T>.empty());
  117. // push instance as light user data
  118. lua_pushlightuserdata(state, instance);
  119. // Set metatable for this type
  120. luaL_getmetatable(state, internal::user_type_name<T>.c_str());
  121. lua_setmetatable(state, -2);
  122. return 1;
  123. }
  124. };
  125. /**
  126. * Register the metatable for user type `T`. This function allows you to register methods
  127. * which are shared across all instances of this type. A garbage-collector hook is also inserted.
  128. * Meta-methods can be added and/or overwritten aswell.
  129. */
  130. template <typename T> static inline
  131. void register_user_type(
  132. State* state,
  133. const std::map<const char*, CFunction>& methods,
  134. const std::map<const char*, CFunction>& meta_methods = {}
  135. ) {
  136. // Setup an appropriate meta table name
  137. if (internal::user_type_name<T>.empty())
  138. internal::user_type_name<T> = "UD#" + std::to_string(internal::user_type_counter++);
  139. luaL_newmetatable(state, internal::user_type_name<T>.c_str());
  140. // Register methods
  141. if (methods.size() > 0 && meta_methods.count("__index") == 0) {
  142. lua_pushstring(state, "__index");
  143. lua_newtable(state);
  144. for (auto& method: methods) {
  145. lua_pushstring(state, method.first);
  146. lua_pushcfunction(state, method.second);
  147. lua_rawset(state, -3);
  148. }
  149. lua_rawset(state, -3);
  150. }
  151. // Register garbage-collection hook
  152. if (meta_methods.count("__gc") == 0) {
  153. lua_pushstring(state, "__gc");
  154. lua_pushcfunction(state, &internal::destruct_user_type<T>);
  155. lua_rawset(state, -3);
  156. }
  157. // Register string representation function
  158. if (meta_methods.count("__tostring") == 0) {
  159. lua_pushstring(state, "__tostring");
  160. lua_pushcfunction(state, &internal::stringify_user_type<T>);
  161. lua_rawset(state, -3);
  162. }
  163. // Insert meta methods
  164. for (const auto& metamethod: meta_methods) {
  165. lua_pushstring(state, metamethod.first);
  166. lua_pushcfunction(state, metamethod.second);
  167. lua_rawset(state, -3);
  168. }
  169. // Pop meta table off the stack
  170. lua_pop(state, -1);
  171. }
  172. /**
  173. * Constructor function for a type `T`. Variadic arguments must be used to specify which parameters
  174. * to use during construction.
  175. */
  176. template <typename T, typename... A>
  177. constexpr CFunction wrap_constructor = &internal::construct_user_type<T, A...>;
  178. /**
  179. * Works similiar to `wrap_function`. Given a class or struct declaration as follows:
  180. *
  181. * struct T {
  182. * R my_method(A0, A1 ... An);
  183. * };
  184. *
  185. * You might wrap this method easily:
  186. *
  187. * CFunction wrapped_meth = wrap_method<T, R(A0, A1 ... An), &T::my_method>;
  188. *
  189. * In Lua, assuming `instance` is a userdata instance of type `T`, x0, x1 ... xn are instances
  190. * of A0, A1 ... An, and the method has been bound as `my_method`; it is possible to invoke the
  191. * method like so:
  192. *
  193. * instance:my_method(x0, x1 ... xn)
  194. */
  195. template <
  196. typename T,
  197. typename S,
  198. typename internal::MethodWrapper<T, S>::MethodPointerType method_pointer
  199. >
  200. constexpr CFunction wrap_method =
  201. wrap_function<
  202. typename internal::MethodWrapper<T, S>::FunctionSignature,
  203. internal::MethodWrapper<T, S>::template delegate<method_pointer>
  204. >;
  205. /**
  206. * Property accessor method
  207. *
  208. * struct T {
  209. * R my_property;
  210. * };
  211. *
  212. * The wrapped property accessor is also a function:
  213. *
  214. * CFunction wrapped_property = wrap_property<T, R, &T::my_property>;
  215. */
  216. template <
  217. typename T,
  218. typename R,
  219. R T::* property_pointer
  220. >
  221. constexpr CFunction wrap_property = &internal::access_user_type_property<T, R, property_pointer>;
  222. LUWRA_NS_END
  223. #endif