读取嵌套的 Lua 表格,其键为 System.Double。

使用 C#和 LuaInterface,我试图读取一个嵌套表,但在尝试打开包含表的键时,我得到一个空的 LuaTable。

.lua 文件:

DB = {
    ["inventory"] = {
        [10001] = {
            ["row"] = 140,
            ["count"] = 20,
        },
        [10021] = {
            ["row"] = 83,
            ["count"] = 3,
        },
        [10075] = {
            ["row"] = 927,
            ["count"] = 15,
        },
    }
}

我可以成功地枚举存储在 inventory 下的条目,通过打开该表:

LuaTable tbl = lua.GetTable("DB.inventory");
foreach (DictionaryEntry de in tbl)
...

但我无法像枚举 inventory 条目时那样打开一个 inventory 条目并枚举它的条目。这是因为键是 System.Double 类型吗?这将失败:

LuaTable tbl = lua.GetTable("DB.inventory.10001");
foreach (DictionaryEntry de in tbl)

抛出一个异常,因为 tbl 是 null。

实际上,一旦我枚举键(inventory 条目),我就想深入嵌套的表并处理其中的内容。正如您所看到的,我无法以我所做的方式获取嵌套表的引用。

原文链接 https://stackoverflow.com/questions/2527310

点赞
stackoverflow用户41661
stackoverflow用户41661

我不知道 Luainterface,但下面的语法

DB.Inventory.10001

在标准的 Lua 中是无效的语法。你尝试过标准的 Lua 语法吗?

DB.Inventory[10001]

这个语法是正确的。

2010-03-26 23:02:45
stackoverflow用户4323
stackoverflow用户4323

看起来 LuaInterface 只支持字符串键。从它的 Lua.cs 可以看出,这个函数最终被你的代码调用:

internal object getObject(string[] remainingPath)
{
        object returnValue=null;
        for(int i=0;i<remainingPath.Length;i++)
        {
                LuaDLL.lua_pushstring(luaState,remainingPath[i]);
                LuaDLL.lua_gettable(luaState,-2);
                returnValue=translator.getObject(luaState,-1);
                if(returnValue==null) break;
        }
        return returnValue;
}

请注意,这段代码调用 lua_pushstring() 将你索引的字符串分开传递,没有为不是字符串的键提供保障。

LuaInterface 采用点分隔的字符串参数的方法是有缺陷的。你已经发现了其中一个缺点;如果你试图查找包含点的键(这在 Lua 是合法的,尽管不是惯用法,有时候,像你发现的那样,表达键的最自然的方式并不是使用类似于 C 标识符的东西),另一个缺陷将会显现出来。

LuaInterface 应该提供一个接受字符串以外类型的键的索引方法。由于它没有,你可以像这样重新编写你的表:

DB = {
    ["inventory"] = {
        ["10001"] = {
            ["row"] = 140,
            ["count"] = 20,
        },
        ["10021"] = {
            ["row"] = 83,
            ["count"] = 3,
        },
        ["10075"] = {
            ["row"] = 927,
            ["count"] = 15,
        },
    }
}

我认为这会起作用。请注意,Norman Ramsey 的建议对于正确的 Lua 是完全合适的,但在 LuaInterface 中会出现问题,因此你应该仍然使用点(.)作为索引符号,就像以前一样(尽管这会看起来像一个 Bug,对于任何普通的 Lua 程序员来说)。

2010-03-28 11:49:26
stackoverflow用户2276554
stackoverflow用户2276554

@Robert Kerr, 你如何知道Inventory Numbers?即10001、10021和10075? 由于您知道返回的表格是采用固定格式的DB、inventory、INV_NUM、row和count,因此可以使用两个循环,一个迭代外部DB.inventory,另一个迭代每个INV_NUM表

Dim tbl As LuaTable = lua.GetTable("DB.inventory")
For Each item As DictionaryEntry In tbl
Debug.Print("{0} = {1}", item.Key, item.Value)
Dim subTbl As LuaTable = item.Value
For Each subItem As DictionaryEntry in subTbl
    Debug.Print("     {0} = {1}", subItem.Key, subItem.Value)
Next
Next

这也适用于非字符串键。

2014-05-17 09:20:15