[PATCH] Enumerator support for LuaTable in LuaInterface

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

[PATCH] Enumerator support for LuaTable in LuaInterface

Zachary P. Landau-4
Hello,

The attached patch implements GetEnumerator(), Keys, and Values for
LuaInterface's LuaTable object.  This allows doing things like the
following in C#:

    LuaTable t = lua.GetTable("a");
    foreach (DictionaryEntry d in t) {
         Console.WriteLine("{0} -> {1}", d.Key, d.Value);
    }

The basic cases I have tested work, but I'd appreciate it if people
would point out any improvements that might be made.

-- 
Zachary P. Landau <[hidden email]>
diff -ur luainterface-1.2.1.orig/src/LuaInterface/Lua.cs luainterface-1.2.1/src/LuaInterface/Lua.cs
--- luainterface-1.2.1.orig/src/LuaInterface/Lua.cs	2004-08-19 17:42:56.000000000 -0400
+++ luainterface-1.2.1/src/LuaInterface/Lua.cs	2005-01-26 12:17:44.000000000 -0500
@@ -5,6 +5,7 @@
 	using System;
 	using System.IO;
 	using System.Collections;
+	using System.Collections.Specialized;
 	using System.Reflection;
 
 	/*
@@ -326,6 +327,24 @@
 			}
 			LuaDLL.lua_settop(luaState,oldTop);
 		}
+
+		public ListDictionary GetTableDict(LuaTable table)
+		{
+			ListDictionary dict = new ListDictionary();
+
+			int oldTop = LuaDLL.lua_gettop(luaState);
+			translator.push(luaState, table);
+			LuaDLL.lua_pushnil(luaState);
+			while (LuaDLL.lua_next(luaState, -2) != 0) 
+			{
+				dict[translator.getObject(luaState, -2)] = translator.getObject(luaState, -1);
+				LuaDLL.lua_settop(luaState, -2);
+			}
+			LuaDLL.lua_settop(luaState, oldTop);
+
+			return dict;
+		}
+
 		/*
 		 * Lets go of a previously allocated reference to a table, function
 		 * or userdata
@@ -515,6 +534,21 @@
 		{
 			return reference;
 		}
+
+		public System.Collections.IEnumerator GetEnumerator()
+		{
+			return interpreter.GetTableDict(this).GetEnumerator();
+		}
+
+		public ICollection Keys 
+		{
+			get { return interpreter.GetTableDict(this).Keys; }
+		}
+
+		public ICollection Values
+		{
+			get { return interpreter.GetTableDict(this).Values; }
+		}
 	}
 
 	public class LuaFunction 
@@ -668,4 +702,4 @@
 		}
 	}
 
-}
\ No newline at end of file
+}
diff -ur luainterface-1.2.1.orig/src/LuaInterface/LuaDLL.cs luainterface-1.2.1/src/LuaInterface/LuaDLL.cs
--- luainterface-1.2.1.orig/src/LuaInterface/LuaDLL.cs	2004-06-16 12:01:28.000000000 -0400
+++ luainterface-1.2.1/src/LuaInterface/LuaDLL.cs	2005-01-26 12:17:48.000000000 -0500
@@ -227,6 +227,8 @@
 		public static extern void lua_error(IntPtr luaState);
 		[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
 		public static extern bool lua_checkstack(IntPtr luaState,int extra);
+		[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
+		public static extern int lua_next(IntPtr luaState,int index);
 	}
 
 }