Pārlūkot izejas kodu

Make NativeFunction's return type to be changable

Ole 9 gadi atpakaļ
vecāks
revīzija
83e6797dc7
2 mainītis faili ar 42 papildinājumiem un 18 dzēšanām
  1. 39 18
      lib/luwra/functions.hpp
  2. 3 0
      tests/functions.cpp

+ 39 - 18
lib/luwra/functions.hpp

@@ -20,31 +20,44 @@ LUWRA_NS_BEGIN
  * A callable native Lua function.
  */
 template <typename R>
-struct NativeFunction: Reference {
+struct NativeFunction {
+	Reference ref;
+
+	inline
+	NativeFunction(const Reference& ref):
+		ref(ref)
+	{}
+
+	inline
 	NativeFunction(State* state, int index):
-		Reference(state, index)
+		ref(state, index)
+	{}
+
+	template <typename T> inline
+	NativeFunction(const NativeFunction<T>& other):
+		ref(other.ref)
 	{}
 
 	inline
 	R operator ()() const {
-		impl->push();
+		ref.impl->push();
 
-		lua_call(impl->state, 0, 1);
-		R returnValue = Value<R>::read(impl->state, -1);
+		lua_call(ref.impl->state, 0, 1);
+		R returnValue = read<R>(ref.impl->state, -1);
 
-		lua_pop(impl->state, 1);
+		lua_pop(ref.impl->state, 1);
 		return returnValue;
 	}
 
 	template <typename... A> inline
 	R operator ()(A&&... args) const {
-		impl->push();
-		size_t numArgs = push(impl->state, std::forward<A>(args)...);
+		ref.impl->push();
+		size_t numArgs = push(ref.impl->state, std::forward<A>(args)...);
 
-		lua_call(impl->state, static_cast<int>(numArgs), 1);
-		R returnValue = Value<R>::read(impl->state, -1);
+		lua_call(ref.impl->state, static_cast<int>(numArgs), 1);
+		R returnValue = read<R>(ref.impl->state, -1);
 
-		lua_pop(impl->state, 1);
+		lua_pop(ref.impl->state, 1);
 		return returnValue;
 	}
 };
@@ -53,23 +66,31 @@ struct NativeFunction: Reference {
  * A callable native Lua function.
  */
 template <>
-struct NativeFunction<void>: Reference {
+struct NativeFunction<void> {
+	Reference ref;
+
+	inline
+	NativeFunction(const Reference& ref):
+		ref(ref)
+	{}
+
+	inline
 	NativeFunction(State* state, int index):
-		Reference(state, index)
+		ref(state, index)
 	{}
 
 	inline
 	void operator ()() const {
-		impl->push();
-		lua_call(impl->state, 0, 0);
+		ref.impl->push();
+		lua_call(ref.impl->state, 0, 0);
 	}
 
 	template <typename... A> inline
 	void operator ()(A&&... args) const {
-		impl->push();
-		size_t numArgs = push(impl->state, std::forward<A>(args)...);
+		ref.impl->push();
+		size_t numArgs = push(ref.impl->state, std::forward<A>(args)...);
 
-		lua_call(impl->state, static_cast<int>(numArgs), 0);
+		lua_call(ref.impl->state, static_cast<int>(numArgs), 0);
 	}
 };
 

+ 3 - 0
tests/functions.cpp

@@ -8,6 +8,9 @@ TEST_CASE("NativeFunction<R>") {
 
 	auto fun = luwra::read<luwra::NativeFunction<int>>(state, -1);
 	REQUIRE(fun(13, 37) == 50);
+
+	luwra::NativeFunction<double> fun2 = fun;
+	REQUIRE(fun2(37.13, 13.37) == 50.5);
 }
 
 TEST_CASE("NativeFunction<void>") {