问题:如何使用C#对象(最好是匿名类型)将C#中的表插入“LuaInterface”脚本范围?
/// I want to do this, but it does not work
/// (complains that 'test' is userdata and not table
/// when I pass it to pairs() in the script)
//lua["test"] = new { A = 1, B = 2 };
/// another option
/// but building this string is a PITA (actual string is nested and long).
lua.DoString("test = { A = 1, B = 2 }");
// So I have to do this
lua.NewTable("test");
((LuaTable) lua["test"])["A"] = 1;
((LuaTable) lua["test"])["B"] = 2;
lua.DoString("for k,v in pairs(test) do print(k..': '..v) end");
答案 0 :(得分:0)
您可以使用要放在表格中的键和值填充C#Dictionary
。然后在“我必须......”部分做你正在做的事情,但是在foreach
循环内。
未经测试的代码:
var test = new Dictionary<string, int> {
{ "A", 1 },
{ "B", 2 }
};
foreach (var entry in test)
{
((LuaTable) lua]["test"])[entry.Key] = entry.Value;
}
我将这个基本思想重构为一个通用类,以增加灵活性。
答案 1 :(得分:0)
我认为如果你想将匿名类型序列化为lua表,你需要用户反射。也许你可以尝试编写一个lua表序列化器。我想我会尝试将我的表组装为字符串并使用DoString将其传递给Lua
我认为字典解决方案很好,你可以使用没有反射的嵌套表。我尝试了元组,但它们不够通用,最终我又回到了反思的想法。
我会创建一个扩展方法:
public static class LuaExt
{
public static LuaTable GetTable(this Lua lua, string tableName)
{
return lua[tableName] as LuaTable;
}
public static LuaTable CreateTable(this Lua lua, string tableName)
{
lua.NewTable(tableName);
return lua.GetTable(tableName);
}
public static LuaTable CreateTable(this Lua lua)
{
lua.NewTable("my");
return lua.GetTable("my");
}
}
然后我可以这样写:
var lua = new Lua();
var table = lua.CreateTable("test");
table["A"] = 1;
table["B"] = 1;
table["C"] = lua.CreateTable();
((LuaTable) table["C"])["A"] = 3;
table["D"] = lua.CreateTable();
((LuaTable)table["D"])["A"] = 3;
foreach (var v in table.Keys)
{
Console.WriteLine(v + ":" + table[v]);
}