Iterate through LuaTable in c#

2.4k views Asked by At

I am trying to iterate through LuaTable object in C#, but getting error.

my lua file is:

config = {}
config.visibility = 0

and my C# code:

LuaTable config = lua.GetTable("config");
Console.WriteLine(config["visibility"].ToString());
foreach (DictionaryEntry member in config)
{
    Console.WriteLine("({0}) {1} = {2}",
        member.Value.GetType().ToString(),
        member.Key,
        member.Value);
}

which produces this output:

0

Unhandled Exception: System.InvalidCastException: Cannot cast from source type to destination type.

If I ask just fot value at key visibility, I get correct answer, but I am unable to iterate through keys and values.

Which class should I use instead of DictionaryEntry?

Thanks, Zbynek

2

There are 2 answers

1
Zbynek On

Well, solution found - following code works:

LuaTable tb = lua.GetTable("config");

Dictionary<object, object> dict = lua.GetTableDict(tb);

foreach (KeyValuePair<object, object> de in dict)
{
    Console.WriteLine("{0} {1}", de.Key.ToString(), de.Value.ToString());
}

I still don't know, why iterating through LuaTable did not work, so I will leave this question open. Also - If I set types of key and value to something different than object (e.g. string and int), it produces Cannot convert type 'System.Collections.Generic.KeyValuePair<string,int>' to 'System.Collections.Generic.KeyValuePair<object,object>' error.

So for now, I leave this as a workaround and any suggestions will be still welcome.

2
Oliver On

Although LuaTable has GetEnumerator/Keys/Values methods, it doesn't inherit from IDictionary. The following might still be applicable: http://lua-users.org/lists/lua-l/2005-01/msg00662.html. See How to use foreach keyword on custom Objects in C# as well. You might have to extend LuaTable or, worse, patch it.