如何填充Lua中的嵌套表?

这一定是非常简单的问题,但我找不到答案:我有一个以这种形式保存数据的文本文件:

| 1 | 1 | A | X |
|   | 2 | A | Z |
|   |   | B | Y |

我想用 Lua 处理这些数据,所以我需要将它们转换成一个结构化(嵌套)的表,如下所示(我希望缩进正确):

t = {
    ['1'] =
    {
        ['1'] =
        {
            {
                { ['A'] = 'X' },
            },
        },
        ['2'] =
        {
            {
                { ['A'] = 'Z' },
                { ['B'] = 'Y' },
            },
        },
    },
}

但我不知道如何实现从 A 到 B 的转换。这个结构已经有点像了,但是我该如何将它读入 Lua 中?

点赞
用户1632532
用户1632532

假设你可以读出一行并获得 | 之间的各个项目,那么算法将类似于这样(伪代码,我将使用 col(n) 表示当前行第 n 列的字符):

1. 存储列 1 和列 2 的当前索引(局部变量)
2. 读取行(如果没有更多行,则进入步骤 73. 如果 col(1) 不为空-将 currentCol1 索引设置为 col(1)
    a. 如果 t[currentCol1] == nil,则 t[currentCol1] = {}
4. 如果 col(2) 不为空-将 currentCol2 索引设置为 col(2)
    a. 如果 t[currentCol1][currentCol2] == nil,则 t[currentCol1][currentCol2] = {}
5. 设置 t[currentCol1][currentCol2][col(3)] = col(4)
6. 进入步骤 2
7. 返回 t

我希望这大部分都是自解释的。除了步骤 2 外,你不应该在伪代码和 Lua 之间有困难(我们不知道你如何获得这些数据,因此无法帮助你解决步骤 2)。如果你不确定表操作,请阅读 这个 lua-users 教程中的 "Tables as arrays" 和 "Tables as dictionaries"。

作为一则侧面记录 - 你的示例似乎把 A=X,A=Z,B=Y 双重嵌套在两个表中。我怀疑你意思是:

['2'] =
    {
        { ['A'] = 'Z' },
        { ['B'] = 'Y' },
    },

而不是:

['2'] =
    {
        {
            { ['A'] = 'Z' },
            { ['B'] = 'Y' },
        },
    },

所以这是伪代码应该为你完成的事情。

2012-09-20 12:52:35
用户1190388
用户1190388

这绝对能为您完成任务。

tTable = {}
OldIDX, OldIDX2, bSwitched, bSwitched2 = 0, 0, false, false

for str in io.lines("txt.txt") do
    local _, _, iDx, iDex, sIdx, sVal = str:find( "^%| ([%d|%s]?) %| ([%d|%s]?) %| (%S?) %| (%S?) %|$" )
    if not tonumber(iDx) then iDx, bSwitched = OldIDX, true end
    if not tonumber(iDex) then iDex, bSwitched2 = OldIDX2, true end
    OldIDX, OldIDX2 = iDx, iDex
    if not bSwitched then
        tTable[iDx] = {}
    end
    if not bSwitched2 then
        tTable[iDx][iDex] = {}
    end
    bSwitched, bSwitched2 = false, false
    tTable[iDx][iDex][sIdx] = sVal
end

注意

你只能更改代码中的文件名。 :)

编辑

看起来我错了,你需要做一些改变。我也已经做过了。

2012-09-20 13:03:12