【问题标题】:how to populate nested tables in Lua?如何在 Lua 中填充嵌套表?
【发布时间】:2012-09-20 07:36:29
【问题描述】:

这一定很容易,但我找不到解决方案:我有一个文本文件,其中的数据是这种形式的:

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

我想用 Lua 处理这些数据,所以我需要将它放在这样的结构化(嵌套)表中(我希望缩进正确):

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

但我不知道如何从 A 转到 B。结构已经存在,但我如何将其读入 Lua?

【问题讨论】:

  • 我什至无法弄清楚你是如何从第一个 sn-p 到第二个的。尝试制定每一步。您将拥有几乎准备好的程序,只需几个单词即可将英语语法更改为 Lua 语法。
  • 我没有从第一块到第二块——这是我的问题。我只是想展示我(认为我)需要的结构,所以我手工编写了 Lua 表,

标签: lua


【解决方案1】:

这肯定会为您完成任务。

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

注意

您可以在代码中更改的唯一内容是文件名。 :)

编辑

好像我错了,你确实需要一些改变。也做了。

【讨论】:

    【解决方案2】:

    假设您可以在一行中读取并获取| 之间的各个项目,算法将是这样的(伪代码,我将使用 col(n) 来指示 n 中的字符'当前行的第 列):

    1. store current indices for columns 1 and 2 (local vars)
    2. read line (if no more lines, go to 7.)
    3. if col(1) not empty - set the currentCol1 index to col(1)
        a. if t[currentCol1] == nil, t[currentCol1] = {}
    4. if col(2) not empty - set the currentCol2 index to col(2)
        a. if t[currentCol1][currentCol2] == nil, t[currentCol1][currentCol2] = {}
    5. set t[currentCol1][currentCol2][col(3)] = col(4)
    6. go to step 2.
    7. return t
    

    我希望这主要是不言自明的。除了第 2 步之外,从伪代码到 lua 应该没有问题(而且我们不知道您如何获取这些数据来帮助您完成第 2 步)。如果您不确定能够执行的操作,我建议您查看this lua-users tutorial 中的“作为数组的表格”和“作为字典的表格”。

    附带说明 - 您的示例似乎将 A=X,A=Z,B=Y 双重嵌套在两个表中。我怀疑不是:

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

    你的意思是:

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

    这就是伪代码应该得到的。

    【讨论】:

    • 我希望我能接受这两个答案;它们相互补充——你的提供解释,巨人的代码。谢谢你俩。你对双嵌套结构是完全正确的;我发现手工写这张表很麻烦......
    猜你喜欢
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多