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
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
(eg 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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.