瀏覽代碼

Add 'getField' function

Ole 10 年之前
父節點
當前提交
073066b5cf
共有 2 個文件被更改,包括 44 次插入21 次删除
  1. 38 21
      lib/luwra/auxiliary.hpp
  2. 6 0
      tests/auxiliary.cpp

+ 38 - 21
lib/luwra/auxiliary.hpp

@@ -12,27 +12,6 @@
 
 LUWRA_NS_BEGIN
 
-namespace internal {
-	template <typename K, typename V, typename... R>
-	struct EntryPusher {
-		static inline
-		void push(State* state, int index, K&& key, V&& value, R&&... rest) {
-			EntryPusher<K, V>::push(state, index, std::forward<K>(key), std::forward<V>(value));
-			EntryPusher<R...>::push(state, index, std::forward<R>(rest)...);
-		}
-	};
-
-	template <typename K, typename V>
-	struct EntryPusher<K, V> {
-		static inline
-		void push(State* state, int index, K&& key, V&& value) {
-			assert(1 == luwra::push(state, key));
-			assert(1 == luwra::push(state, value));
-			lua_rawset(state, index < 0 ? index - 2 : index);
-		}
-	};
-}
-
 /**
  * Check if two values are equal.
  */
@@ -67,6 +46,27 @@ V getGlobal(State* state, const std::string& name) {
 	return instance;
 }
 
+namespace internal {
+	template <typename K, typename V, typename... R>
+	struct EntryPusher {
+		static inline
+		void push(State* state, int index, K&& key, V&& value, R&&... rest) {
+			EntryPusher<K, V>::push(state, index, std::forward<K>(key), std::forward<V>(value));
+			EntryPusher<R...>::push(state, index, std::forward<R>(rest)...);
+		}
+	};
+
+	template <typename K, typename V>
+	struct EntryPusher<K, V> {
+		static inline
+		void push(State* state, int index, K&& key, V&& value) {
+			assert(1 == luwra::push(state, key));
+			assert(1 == luwra::push(state, value));
+			lua_rawset(state, index < 0 ? index - 2 : index);
+		}
+	};
+}
+
 /**
  * Set multiple fields at once. Allows you to provide multiple key-value pairs.
  */
@@ -76,6 +76,23 @@ void setFields(State* state, int index, R&&... args) {
 	internal::EntryPusher<R...>::push(state, index, std::forward<R>(args)...);
 }
 
+/**
+ * Retrieve a field from a table.
+ */
+template <typename V, typename K> static inline
+V getField(State* state, int index, K key) {
+	if (index < 0)
+		index = lua_gettop(state) + (index + 1);
+
+	assert(push<K>(state, key) == 1);
+	lua_rawget(state, index);
+
+	V value = read<V>(state, -1);
+	lua_pop(state, 1);
+
+	return value;
+}
+
 /**
  * Create a new table and set its fields.
  */

+ 6 - 0
tests/auxiliary.cpp

@@ -52,3 +52,9 @@ TEST_CASE("setFields") {
 	REQUIRE(luwra::read<int>(state, -1) == 456);
 }
 
+TEST_CASE("getField") {
+	luwra::StateWrapper state;
+
+	REQUIRE(luaL_dostring(state, "return {hello = 123}") == LUA_OK);
+	REQUIRE(luwra::getField<int>(state, -1, "hello") == 123);
+}