lua在表格中打印特定的键/值对

时间:2013-04-15 23:03:15

标签: lua

我有一个外部lua表,其结构如下:

sgeT = {
  [2535047] = {
  {
      ["account"] = "TG-MCB110105",
      ["exec"] = "/share/home/00288/tg455591/NAMD_2.8b3/NAMD_2.8b3_Linux-x86_64-MVAPICH-Intel-Ranger/namd2",
      ["execEpoch"] = 1305825864,
      ["execModify"] = "Thu May 19 12:24:24 2011",
      ["execType"] = "user:binary",
      ["jobID"] = "2535047",
      ["numCores"] = "128",
      ["numNodes"] = "8",
      pkgT = {
      },
      ["runTime"] = "65125",
      ["sha1"] = "e157dd510a7be4d775d6ceb271373ea24e7f9559",
      sizeT = {
         ["bss"] = "104552",
         ["data"] = "192168",
         ["text"] = "10650813",
      },
      ["startEpoch"] = "1335843433",
      ["startTime"] = "Mon Apr 30 22:37:13 2012",
      ["user"] = "guo",
      },
  },
  [2535094] = {
  {
     ["account"] = "TG-MCB110105",
     ["exec"] = "/share/home/00288/tg455591/NAMD_2.8b3/NAMD_2.8b3_Linux-x86_64-MVAPICH-Intel-Ranger/namd2",
     ["execEpoch"] = 1305825864,
     ["execModify"] = "Thu May 19 12:24:24 2011",
     ["execType"] = "user:binary",
     ["jobID"] = "2535094",
     ["numCores"] = "128",
     ["numNodes"] = "8",
     pkgT = {
     },
     ["runTime"] = "81635",
     ["sha1"] = "e157dd510a7be4d775d6ceb271373ea24e7f9559",
     sizeT = {
        ["bss"] = "104552",
        ["data"] = "192168",
        ["text"] = "10650813",
     },
     ["startEpoch"] = "1335823028",
     ["startTime"] = "Mon Apr 30 16:57:08 2012",
     ["user"] = "guo",
     },
  },

我正在尝试使用以下lua脚本来打印exec键/值对,如下所示:

function DeepPrint (e)
   if type(e) == "table" then
       for k,v in pairs(e) do 
          if k == "exec" then
            print(k)
            DeepPrint(v)       
          end
       end
   else 
    print(e)
   end
 end


FileStr = "lariatData-sgeT-2012-05-01_2.lua"
Hnd, ErrStr = io.open(FileStr, "r")
if Hnd then
    dofile(FileStr)
    for Str in Hnd:lines() do       
        DeepPrint(sgeT)            
    end
Hnd.close()
else
    print(ErrStr, "\n")
end

理想情况下,我想打印数字索引和exec值,例如:

2535047 execVal

但是,运行代码时没有任何返回。最初数字索引没有用方括号括起来,但我添加了它们以便能够读取文件。但是,鉴于它们不是顺序的,我不能像数组那样循环遍历它们,但我相信这些数字索引可能是我问题的根源。我不确定我的代码有什么问题,但它什么也没有返回。任何人都可以推荐我如何修复代码,以便我可以获得适当的键和值返回?在此先感谢!!!

2 个答案:

答案 0 :(得分:1)

由于您的表格具有固定的结构,因此您只需使用语法糖sgeT[key1][key2]即可访问exec键。

for i, v in pairs( sgeT ) do
  print( i, v[1].exec )
end

以下是一个工作示例:http://eval.in/16460

答案 1 :(得分:1)

您正在迭代文件中的行,但您已经处理并加载了该文件(作为Lua块),因此不再需要它。就这样做:

dofile(FileStr)
DeepPrint(sgeT)

主要问题是你只能递归调用DeepPrint那些值为exec的键,但是第一级的键都没有(所以没有打印,因为你没有去超越第一级)。您可能需要在致电if之前关闭DeepPrint

function DeepPrint (e)
   if type(e) == "table" then
       for k,v in pairs(e) do 
          if k == "exec" then
            print(k)
          end
          DeepPrint(v)       
       end
   else 
    print(e)
   end
 end