1

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

.lua 文件:

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

通过使用以下命令打开该表,我可以成功地 foreach 库存下的条目:

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

我不能做的是打开一个库存项目并以相同的方式枚举其条目。这是因为密钥是System.Double类型吗?这失败了:

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

有一个例外,因为 tbl 为空。

实际上,一旦我枚举了键(库存项目),我就想深入到嵌套表中并使用这些内容。如您所见,我无法以我的方式获得对嵌套表的引用。

4

3 回答 3

3

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 采用点分隔的字符串参数的方式operator[]()是有缺陷的。你发现了一个缺点;如果您尝试查找其中实际上有一个点的键(这是合法的 Lua - 虽然不是惯用的,但有时您会发现表达键的最自然方式不是使用某些东西)会出现另一个看起来像一个 C 标识符)。

LuaInterface 应该提供的是一个索引方法,它采用字符串以外的类型。因为它没有,你可以像这样重写你的表:

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

我认为这会奏效。请注意,Norman Ramsey 的建议虽然完全适用于适当的 Lua,但会在 LuaInterface 中中断,因此您应该像以前一样单独使用点进行索引(尽管这对于任何普通的 Lua 程序员来说都是一个错误)。

于 2010-03-28T11:49:26.497 回答
2

我不知道Luainterface,但是语法

DB.Inventory.10001

在标准 Lua 中不是有效的语法。你有没有尝试过

DB.Inventory[10001]

在标准 Lua 中哪个是正确的?

于 2010-03-26T23:02:45.403 回答
0

@Robert Kerr,您怎么知道库存编号?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-17T09:20:15.680 回答