2012-09-20 66 views
2

这一定是令人尴尬的容易,但我不能找到解决办法:我有这种形式的数据的文本文件:如何在Lua中填充嵌套表?

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

我想处理和Lua这个数据,所以我需要有它在结构化(嵌套)表是这样的(我希望压痕出来右):

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

但我无法弄清楚如何从A到B的结构已经是样的都有,但我怎样才能将它读入Lua?

+3

我什至不能算出你是如何从第一个片段获得第二。尝试制定每一步。你几乎已经准备好只用几句话就可以从英语变成Lua语法的程序。 –

+0

我没有从第一块到第二块 - 这是我的问题。我只是想展示我认为我需要的结构,所以我亲手写了Lua表, – Thomas

回答

2

这绝对会为你做任务。

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 

注:

您可以更改代码的唯一的事情是文件的名称。 :)

编辑

好像我错了,你确实需要一些改变。也制作它们。

1

假设你可以读一行,并获得|之间的单个项目,算法会是这样的(伪代码,我会用col(n)来表示n' th列当前行):

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开始重复“Tables as arrays”和“Tables as dictionaries”。作为一个方面说明 - 你的例子似乎是在两个表格中对A = X,A = Z,B = Y进行双重嵌套。我怀疑是不是:

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

你的意思是:

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

所以这是伪代码应该得到你。

+0

我希望我能接受这两个答案;它们相互补充 - 你们提供了解释,巨人的代码。谢谢你们俩。你对双嵌套结构是完全正确的;我发现手工写这张桌子很麻烦...... – Thomas