Selaa lähdekoodia

Add property accessors

Ole Krüger 10 vuotta sitten
vanhempi
commit
9092338f02
1 muutettua tiedostoa jossa 30 lisäystä ja 0 poistoa
  1. 30 0
      lib/luwra/usertypes.hpp

+ 30 - 0
lib/luwra/usertypes.hpp

@@ -52,6 +52,18 @@ namespace internal {
 		);
 	}
 
+	template <typename T, typename R, R T::* PropertyPointer>
+	int UserTypeAccessor(State* state) {
+		if (lua_gettop(state) > 1) {
+			// Setter
+			(Value<T&>::Read(state, 1).*PropertyPointer) = Value<R>::Read(state, 2);
+			return 0;
+		} else {
+			// Getter
+			return Value<R>::Push(state, Value<T&>::Read(state, 1).*PropertyPointer);
+		}
+	}
+
 	template <typename T, typename S>
 	struct MethodWrapper {
 		static_assert(
@@ -233,6 +245,24 @@ constexpr CFunction WrapMethod =
 		internal::MethodWrapper<T, S>::template Delegate<MethodPointer>
 	>;
 
+/**
+ * Property accessor method
+ *
+ *   struct T {
+ *     R my_property;
+ *   };
+ *
+ * The wrapped property accessor is also a function:
+ *
+ *   CFunction wrapped_property = WrapProperty<T, R, &T::my_property>;
+ */
+template <
+	typename T,
+	typename R,
+	R T::* PropertyPointer
+>
+constexpr CFunction WrapProperty = &internal::UserTypeAccessor<T, R, PropertyPointer>;
+
 LUWRA_NS_END
 
 #endif