Search code examples
c#luaiteratorluainterface

Iterate through LuaTable in c#


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


Solution

  • 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.