usertypes.hpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. LUWRA_NS_BEGIN
  14. namespace internal {
  15. using UserTypeID = const void*;
  16. template <typename T>
  17. using CleanUserType =
  18. std::remove_pointer_t<std::remove_reference_t<std::remove_cv_t<T>>>;
  19. /**
  20. * User type identifier
  21. */
  22. template <typename T>
  23. UserTypeID user_type_id = (void*) INTPTR_MAX;
  24. /**
  25. * Registry name for a meta table which is associated with a user type
  26. */
  27. template <typename T>
  28. std::string user_type_reg_name =
  29. "UD#" + std::to_string(uintptr_t(&user_type_id<CleanUserType<T>>));
  30. /**
  31. * Register a new meta table for a user type T.
  32. */
  33. template <typename T> static inline
  34. void new_user_type_id(State* state) {
  35. luaL_newmetatable(state, user_type_reg_name<CleanUserType<T>>.c_str());
  36. // Use the address as user type identifier
  37. UserTypeID ut_id = lua_topointer(state, -1);
  38. user_type_id<CleanUserType<T>> = ut_id;
  39. }
  40. /**
  41. * Get the identifier for a user type at the given index.
  42. */
  43. static inline
  44. UserTypeID get_user_type_id(State* state, int index) {
  45. if (!lua_isuserdata(state, index))
  46. return nullptr;
  47. if (lua_getmetatable(state, index)) {
  48. UserTypeID type_id = lua_topointer(state, -1);
  49. lua_pop(state, 1);
  50. return type_id;
  51. } else {
  52. return nullptr;
  53. }
  54. }
  55. /**
  56. * Check if the value at the given index if a user type T.
  57. */
  58. template <typename T> static inline
  59. T* check_user_type(State* state, int index) {
  60. UserTypeID uid = get_user_type_id(state, index);
  61. if (uid == user_type_id<CleanUserType<T>>) {
  62. return static_cast<T*>(lua_touserdata(state, index));
  63. } else {
  64. std::string error_msg =
  65. "Expected user type " + std::to_string(uintptr_t(user_type_id<CleanUserType<T>>));
  66. luaL_argerror(state, index, error_msg.c_str());
  67. return nullptr;
  68. }
  69. }
  70. template <typename T> static inline
  71. void apply_user_type_meta_table(State* state) {
  72. luaL_getmetatable(state, user_type_reg_name<CleanUserType<T>>.c_str());
  73. lua_setmetatable(state, -2);
  74. }
  75. /**
  76. * Lua C function to construct a user type T with parameters A
  77. */
  78. template <typename T, typename... A> static inline
  79. int construct_user_type(State* state) {
  80. return internal::Layout<int(A...)>::direct(
  81. state,
  82. 1,
  83. &Value<T&>::template push<A...>,
  84. state
  85. );
  86. }
  87. /**
  88. * Lua C function to destruct a user type T
  89. */
  90. template <typename T> static inline
  91. int destruct_user_type(State* state) {
  92. if (!lua_islightuserdata(state, 1))
  93. Value<T&>::read(state, 1).~T();
  94. return 0;
  95. }
  96. /**
  97. * Create a string representation for user type T.
  98. */
  99. template <typename T> static
  100. std::string stringify_user_type(T& val) {
  101. return
  102. internal::user_type_reg_name<CleanUserType<T>>
  103. + "@"
  104. + std::to_string(uintptr_t(&val));
  105. }
  106. /**
  107. * Lua C function for a property accessor.
  108. */
  109. template <typename T, typename R, R T::* property_pointer> static inline
  110. int access_user_type_property(State* state) {
  111. if (lua_gettop(state) > 1) {
  112. // Setter
  113. (Value<T&>::read(state, 1).*property_pointer) = Value<R>::read(state, 2);
  114. return 0;
  115. } else {
  116. // Getter
  117. return push(state, Value<T&>::read(state, 1).*property_pointer);
  118. }
  119. }
  120. template <typename T, typename S>
  121. struct MethodWrapper {
  122. static_assert(
  123. sizeof(T) == -1,
  124. "The MethodWrapper template expects a type name and a function signature as parameter"
  125. );
  126. };
  127. template <typename T, typename R, typename... A>
  128. struct MethodWrapper<T, R(A...)> {
  129. using MethodPointerType = R (T::*)(A...);
  130. using FunctionSignature = R (T&, A...);
  131. /**
  132. * This function is a wrapped around the invocation of a given method.
  133. */
  134. template <MethodPointerType method_pointer> static inline
  135. R call(T& parent, A... args) {
  136. return (parent.*method_pointer)(std::forward<A>(args)...);
  137. }
  138. };
  139. }
  140. /**
  141. * User type T.
  142. * Instances created using this specialization are allocated and constructed as full user data
  143. * types in Lua. The default garbage-collecting hook will destruct the user type, once it has
  144. * been marked.
  145. */
  146. template <typename T>
  147. struct Value<T&> {
  148. static inline
  149. T& read(State* state, int n) {
  150. return *internal::check_user_type<T>(state, n);
  151. }
  152. template <typename... A> static inline
  153. int push(State* state, A&&... args) {
  154. void* mem = lua_newuserdata(state, sizeof(T));
  155. if (!mem) {
  156. luaL_error(state, "Failed to allocate user type");
  157. return -1;
  158. }
  159. // Call constructor on instance
  160. new (mem) T(std::forward<A>(args)...);
  161. // Set metatable for this type
  162. internal::apply_user_type_meta_table<T>(state);
  163. return 1;
  164. }
  165. };
  166. /**
  167. * User type T.
  168. * Instances created using this specialization are allocated as light user data in Lua.
  169. * The default garbage-collector does not destruct light user data types.
  170. */
  171. template <typename T>
  172. struct Value<T*> {
  173. static inline
  174. T* read(State* state, int n) {
  175. return internal::check_user_type<T>(state, n);
  176. }
  177. static inline
  178. int push(State* state, T* instance) {
  179. // push instance as light user data
  180. lua_pushlightuserdata(state, instance);
  181. // Set metatable for this type
  182. internal::apply_user_type_meta_table<T>(state);
  183. return 1;
  184. }
  185. };
  186. /**
  187. * Constructor function for a type `T`. Variadic arguments must be used to specify which parameters
  188. * to use during construction.
  189. */
  190. template <typename T, typename... A>
  191. constexpr CFunction wrap_constructor = &internal::construct_user_type<T, A...>;
  192. /**
  193. * Works similiar to `wrap_function`. Given a class or struct declaration as follows:
  194. *
  195. * struct T {
  196. * R my_method(A0, A1 ... An);
  197. * };
  198. *
  199. * You might wrap this method easily:
  200. *
  201. * CFunction wrapped_meth = wrap_method<T, R(A0, A1 ... An), &T::my_method>;
  202. *
  203. * In Lua, assuming `instance` is a userdata instance of type `T`, x0, x1 ... xn are instances
  204. * of A0, A1 ... An, and the method has been bound as `my_method`; it is possible to invoke the
  205. * method like so:
  206. *
  207. * instance:my_method(x0, x1 ... xn)
  208. */
  209. template <
  210. typename T,
  211. typename S,
  212. typename internal::MethodWrapper<T, S>::MethodPointerType method_pointer
  213. >
  214. constexpr CFunction wrap_method =
  215. wrap_function<
  216. typename internal::MethodWrapper<T, S>::FunctionSignature,
  217. internal::MethodWrapper<T, S>::template call<method_pointer>
  218. >;
  219. /**
  220. * Property accessor method
  221. *
  222. * struct T {
  223. * R my_property;
  224. * };
  225. *
  226. * The wrapped property accessor is also a function:
  227. *
  228. * CFunction wrapped_property = wrap_property<T, R, &T::my_property>;
  229. */
  230. template <
  231. typename T,
  232. typename R,
  233. R T::* property_pointer
  234. >
  235. constexpr CFunction wrap_property =
  236. &internal::access_user_type_property<T, R, property_pointer>;
  237. /**
  238. * Register the metatable for user type `T`. This function allows you to register methods
  239. * which are shared across all instances of this type. A garbage-collector hook is also inserted.
  240. * Meta-methods can be added and/or overwritten aswell.
  241. */
  242. template <typename T> static inline
  243. void register_user_type(
  244. State* state,
  245. const std::map<const char*, CFunction>& methods,
  246. const std::map<const char*, CFunction>& meta_methods = std::map<const char*, CFunction>()
  247. ) {
  248. // Setup an appropriate meta table name
  249. internal::new_user_type_id<T>(state);
  250. // Register methods
  251. if (methods.size() > 0 && meta_methods.count("__index") == 0) {
  252. push(state, "__index");
  253. lua_newtable(state);
  254. for (auto& method: methods) {
  255. push(state, method.first);
  256. push(state, method.second);
  257. lua_rawset(state, -3);
  258. }
  259. lua_rawset(state, -3);
  260. }
  261. // Register garbage-collection hook
  262. if (meta_methods.count("__gc") == 0) {
  263. push(state, "__gc");
  264. push(state, &internal::destruct_user_type<T>);
  265. lua_rawset(state, -3);
  266. }
  267. // Register string representation function
  268. if (meta_methods.count("__tostring") == 0) {
  269. push(state, "__tostring");
  270. push(state, wrap_function<std::string(T&), &internal::stringify_user_type<T>>);
  271. lua_rawset(state, -3);
  272. }
  273. // Insert meta methods
  274. for (const auto& metamethod: meta_methods) {
  275. push(state, metamethod.first);
  276. push(state, metamethod.second);
  277. lua_rawset(state, -3);
  278. }
  279. // Pop meta table off the stack
  280. lua_pop(state, -1);
  281. }
  282. LUWRA_NS_END
  283. #endif