6

我有一个外部 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

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

2535047 execVal

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

4

2 回答 2

3

由于您的表具有固定的结构,您可以简单地使用语法糖sgeT[key1][key2]来访问exec键。

for i, v in pairs( sgeT ) do
  print( i, v[1].exec )
end
于 2013-04-16T03:47:32.463 回答
2

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

dofile(FileStr)
DeepPrint(sgeT)

主要问题是你只DeepPrint递归地调用那些具有 valueexec的键,但第一级的键都没有(所以没有任何东西被打印,因为你没有超出第一级)。您可能需要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
于 2013-04-16T04:58:57.990 回答