usertypes.hpp 7.9 KB

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