Torch:CmdLine():将元素数组从命令行传递给变量

Torch: CmdLine() : passing array of elements to a variable from command line

我正在使用 torch.CmdLine() 来解析 Torch 中的命令行参数。我需要为其中一个变量传递一个元素数组。我不知道为变量传递元素数组的任何机制。因此,我将该变量视为一个字符串,并在命令行中传递由 space 分隔并括在双引号内的元素数组。 执行此操作的代码如下所示:

cmd = torch.CmdLine()
cmd:text('Training')
cmd:text()
cmd:option('-cuda_device',"1 2 3")
params = cmd:parse(arg or {})

--parse the string to extract array of numbers
for i=1,string.len(params.cuda_device) do
    if params.cuda_device[i] ~= ' ' then
       -- some code here
    end
end

这里因为默认不提供Lua字符串索引,我不得不重写__index以启用字符串索引,如下所示,

getmetatable('').__index = function(str,i) return string.sub(str,i,i) end

这适用于将字符串解析为数字数组。

但是,重写 __index 会破坏其他地方的代码,引发以下错误:

qlua: /home/torch/install/share/lua/5.1/torch/init.lua:173: bad argument #2 to '__index' (number expected, got string)

我可以做一些解决方法来解决这个问题(而不是覆盖 __index 直接使用 string.sub(str,i,i))但是我想知道你在传递数组时的建议以优雅的方式使用 torch.CmdLine() 的元素——如果适用的话。

提前致谢。

您可以将列表作为由空格分隔的单词序列传递,在 cmd:parse 之后,您可以使用以下方法将字符串分解为数组:

params = cmd:parse()
local tmptab = {}
for word in params.cuda_device:gmatch("%w+") do
  tmptab[#tmptab +1] = word
end
params.cuda_device = tmptab
for i,v in pairs(params.cuda_device) do
   -- some code here
end

这会将 cmd:parse() 解析的字符串分解为 table,每个单词都在索引上,并且无需深入研究字符串元方法...

另外,这样做可以避免错误:

getmetatable('').__index = function(str,i)
  if(type(i) == "number") then
    return string.sub(str,i,i)
  else
    return ""
  end 
end

奇怪的是您尝试使用另一个字符串索引一个字符串,但是...