[英]Iterate through LuaTable in c#
我试图通过C#中的LuaTable对象进行迭代,但出现错误。
我的lua文件是:
config = {}
config.visibility = 0
和我的C#代码:
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);
}
产生以下输出:
0
Unhandled Exception: System.InvalidCastException: Cannot cast from source type to destination type.
如果仅在键visibility
询问值,我会得到正确的答案,但是我无法遍历键和值。
我应该使用哪个类而不是DictionaryEntry?
谢谢Zbynek
好了,找到了解决方案-以下代码有效:
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());
}
我仍然不知道,为什么通过LuaTable进行迭代无效,所以我将这个问题保留为开放状态。 另外-如果我将键和值的类型设置为与object
不同的值(例如string
和int
),它将产生Cannot convert type 'System.Collections.Generic.KeyValuePair<string,int>' to 'System.Collections.Generic.KeyValuePair<object,object>'
错误。
因此,现在,我将其作为解决方法,仍然欢迎任何建议。
尽管LuaTable具有GetEnumerator / Keys / Values方法,但它并不继承自IDictionary。 以下内容可能仍然适用: http : //lua-users.org/lists/lua-l/2005-01/msg00662.html 。 另请参见如何在C#中的自定义对象上使用foreach关键字 。 您可能必须扩展LuaTable或更糟糕的是对其进行修补。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.