开发者

LuaInterface: add a table to the script scope

开发者 https://www.devze.com 2023-01-02 23:36 出处:网络
Question: how can I insert a table from C# into \'LuaInterface\' script scope using a C# object (preferably anonymous type)?

Question: how can I insert a table from C# into 'LuaInterface' script scope using a C# object (preferably anonymous type)?

/// 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 = 开发者_JAVA百科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");


You could fill a C# Dictionary with the keys and values you want to put inside the table. Then do what you're doing in the "I have to..." section, but inside a foreach loop.

Untested code:

var test = new Dictionary<string, int> {
    { "A", 1 },
    { "B", 2 }
};

foreach (var entry in test)
{
    ((LuaTable) lua]["test"])[entry.Key] = entry.Value;
}

I'd refactor this basic idea into a generic class for added flexibility.


I think if you want to serialize anonymous types into lua tables you will need to user reflection. Maybe you can try to write a lua table serializer. I think I would try to assemble my tables as string and pass it to Lua with DoString

I think the dictionary solution is good and you can use nested tables with without reflection. I tried Tuples, but they are not generic enough and eventually I fell back to the reflection idea.

I would create an extension method:

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");
    }
}

Then I could write something like this:

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]);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消