【问题标题】:LuaInterface - a function which will return a LuaTable valueLuaInterface - 一个返回 LuaTable 值的函数
【发布时间】:2013-01-13 01:06:30
【问题描述】:

有谁知道如何编写一个返回 LuaTable 值的 C# 函数(例如 {1 = "example1", 2 = 234, "foo" = "Foo Example"}? 我测试过的所有类型都返回LuaUserData 值,这些值是不可配对/可配对的。 提前致谢。

--更新-- 在我看来,最接近 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,无法配对/配对

【问题讨论】:

  • 请提供源示例,了解您当前如何在 C# 端构建表及其值。你在使用什么函数,你是如何使用 Lua 虚拟栈的?
  • 您可能还会发现这篇堆栈溢出文章很有帮助。 stackoverflow.com/questions/10941563/…
  • 我已经找到了这种方式,但我正在寻找c#解决方案。
  • 不确定您所说的“c# 解决方案”是什么意思,因为 stackoverflow 文章是 C#。问题是 Lua 引擎是用 C 编程语言编写的,所以你必须有一个 C# 到 C 的接口才能在两者之间进行编组和转换。在 C 或 C++ 中,直接使用 Lua 引擎中提供的函数就可以了,这些函数允许您在 Lua 虚拟堆栈上构建表等,然后调用将构建的表提供给 Lua 引擎的函数。

标签: c# lua luainterface


【解决方案1】:

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

首先是,让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"]

【讨论】:

    【解决方案2】:

    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;
    

    我还写了一个 marshall 函数,它使用我上面的函数将 Dictionary 转换为 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;
    }
    

    【讨论】:

      【解决方案3】:

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

      使用 JCH2k 逻辑,我能够使这个函数将 c# Point 转换为 LuaTable。

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

      在 Lua 中使用一次 return。

      local x = val[1]
      local y = val[2]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-15
        • 2014-01-03
        • 1970-01-01
        • 1970-01-01
        • 2011-05-10
        • 2011-08-26
        • 2020-11-20
        • 1970-01-01
        相关资源
        最近更新 更多