LuaInterface - 一个将返回 LuaTable 值的函数。

有没有人知道如何编写一个 C# 函数,以返回一个 LuaTable 值(例如 { 1 = "example1",2 = 234,“foo” =“Foo Example”})?

我测试过的所有类型都返回 LuaUserData 值,这些值无法成为 pair/ipair。

提前致谢。

-更新-

我认为与 luaTable 最接近的类型是 ListDictionary

    [LuaFunc(Name = "table", Desc = "returns test LuaTable", Params = new string[] { })]
    public System.Collections.Specialized.ListDictionary table()
    {
        var k = new System.Collections.Specialized.ListDictionary(){
            {"1",1},
            {2,"2"}
        };

        return k;
    }

但在 Lua 中仍被识别为 LuaUserData,无法成为 pair/ipair。

点赞
用户1829325
用户1829325

这个问题有两个可能的解决方案。

第一种方法是让 Lua 返回表格:

LuaTable lt = (LuaTable) lua.DoString("return {1 = "example1", 2 = 234, "foo" = "Foo Example"}")[0];

第二种方法是创建一个新表格:

LuaTable lt = lua.NewTable("ThisTable")
lt["1"] = "example1"
lt["2"] = 234
lt["foo"] = "Foo Example"

你可以通过以下方式从 Lua 访问第二个表格:

ThisTable[1] = ThisTable["foo"]
2013-01-22 13:59:33
用户1070906
用户1070906

user1829325 提供了非常好的方法,但是它们在不进行修改的情况下无法编译。

lua.DoString返回一个数组,而lua.NewTable不返回任何内容。

但是,它引导我找到了以下解决方案,它运行得非常完美,因此仍然给予 +1!

public LuaTable CreateTable()
{
    return (LuaTable)lua.DoString("return {}")[0];
}

一个从Lua调用的应该返回一个表的C#函数可能看起来像这样:

LuaTable newtable = CreateTable();
table["lala"] = 5;
return table;

我还编写了一个马歇尔函数,它使用我的上面的函数将字典转换为LuaTable:

private LuaTable MarshalDictionaryToTable<A,B>(Dictionary<A, B> dict)
{
    LuaTable table = runner.CreateTable();
    foreach (KeyValuePair<A, B> kv in dict)
        table[kv.Key] = kv.Value;
    return table;
}
2013-08-28 11:44:00
用户2951148
用户2951148

JCH2k是对的。NewTable 没有返回值类型!

使用 JCH2k 的逻辑,我可以制作出此函数,将一个 c# 的 Point 对象转换为 LuaTable。

public LuaTable ConvertPointToTable(Point point)
{
return (LuaTable)lua.DoString("return {" + point.X + ", " + point.Y + "}")[0];
}

使用一次返回值在 Lua 中。

local x = val[1]
local y = val[2]
2013-11-04 01:33:23