ソースを参照

Make function objects readable

Ole 9 年 前
コミット
8daaf5808b
共有2 個のファイルを変更した45 個の追加14 個の削除を含む
  1. 11 1
      lib/luwra/functions.hpp
  2. 34 13
      tests/functions.cpp

+ 11 - 1
lib/luwra/functions.hpp

@@ -10,6 +10,9 @@
 #include "common.hpp"
 #include "types.hpp"
 #include "stack.hpp"
+#include "usertypes.hpp"
+
+#include <functional>
 
 LUWRA_NS_BEGIN
 
@@ -74,7 +77,6 @@ template <typename R>
 struct Value<NativeFunction<R>> {
 	static inline
 	NativeFunction<R> read(State* state, int index) {
-		luaL_checktype(state, index, LUA_TFUNCTION);
 		return {state, index};
 	}
 
@@ -84,6 +86,14 @@ struct Value<NativeFunction<R>> {
 	}
 };
 
+template <typename R, typename... A>
+struct Value<std::function<R(A...)>> {
+	static inline
+	std::function<R(A...)> read(State* state, int index) {
+		return {Value<NativeFunction<R>>::read(state, index)};
+	}
+};
+
 LUWRA_NS_END
 
 #endif

+ 34 - 13
tests/functions.cpp

@@ -1,23 +1,44 @@
 #include <catch.hpp>
 #include <luwra.hpp>
 
-TEST_CASE("NativeFunction") {
+TEST_CASE("NativeFunction<R>") {
 	luwra::StateWrapper state;
 
-	SECTION("with return value") {
-		REQUIRE(state.runString("return function (x, y) return x + y end") == LUA_OK);
+	REQUIRE(state.runString("return function (x, y) return x + y end") == LUA_OK);
 
-		auto fun = luwra::read<luwra::NativeFunction<int>>(state, -1);
-		REQUIRE(fun(13, 37) == 50);
-	}
+	auto fun = luwra::read<luwra::NativeFunction<int>>(state, -1);
+	REQUIRE(fun(13, 37) == 50);
+}
+
+TEST_CASE("NativeFunction<void>") {
+	luwra::StateWrapper state;
+
+	REQUIRE(state.runString("return function (x, y) returnValue = x + y end") == LUA_OK);
+
+	auto fun = luwra::read<luwra::NativeFunction<void>>(state, -1);
+	fun(13, 37);
+
+	int returnValue = state.get<int>("returnValue");
+	REQUIRE(returnValue == 50);
+}
+
+TEST_CASE("function<R(A...)>") {
+	luwra::StateWrapper state;
+
+	REQUIRE(state.runString("return function (x, y) return x + y end") == LUA_OK);
+
+	auto fun = luwra::read<std::function<int(int, int)>>(state, -1);
+	REQUIRE(fun(13, 37) == 50);
+}
+
+TEST_CASE("function<void(A...)>") {
+	luwra::StateWrapper state;
 
-	SECTION("without return value") {
-		REQUIRE(state.runString("return function (x, y) returnValue = x + y end") == LUA_OK);
+	REQUIRE(state.runString("return function (x, y) returnValue = x + y end") == LUA_OK);
 
-		auto fun = luwra::read<luwra::NativeFunction<void>>(state, -1);
-		fun(13, 37);
+	auto fun = luwra::read<std::function<void(int, int)>>(state, -1);
+	fun(13, 37);
 
-		int returnValue = state.get<int>("returnValue");
-		REQUIRE(returnValue == 50);
-	}
+	int returnValue = state.get<int>("returnValue");
+	REQUIRE(returnValue == 50);
 }