1

I am using torch.CmdLine() to parse command line arguments in Torch. I need to pass an array of elements for one of the variables. I am not aware of any mechanisms for passing an array of elements for a variable. So I am treating that variable as a string and passing the array of elements separated by space and enclosed within double quotes from the command line. The code for doing this looks as follows:

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

Here since Lua string indexing is not provided by default, I had to override __index to enable indexing of string as follows,

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

This works for parsing the string to an array of numbers.

However, overriding __index breaks the code somewhere else, throwing the following error:

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

I can do some workarounds to fix this (instead of overriding __index use string.sub(str,i,i) directly) but I would like to know your suggestions in passing an array of elements using torch.CmdLine() in an elegant way--if applicable.

Thanks in Advance.

Arul
  • 303
  • 1
  • 5
  • 16
  • Hey! check the docs: https://github.com/torch/torch7/blob/master/doc/cmdline.md#table-parsearg and this answer http://stackoverflow.com/questions/32379841/lua-cmd-line-string . Hope it helps! – Manuel Lagunas Jan 04 '17 at 20:00
  • @ManuelLagunas Ya I am doing something very similar. But I was wondering if I can pass the array of elements in some other format other than a string. Thanks for your suggestion. – Arul Jan 05 '17 at 09:56

1 Answers1

0

You can pass the list as a sequence of words separated by spaces as you have done, and after cmd:parse you can explode the string into an array using:

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

That will explode the string parsed by cmd:parse() into an table with each word on it's on index, and there would be no need to delve into string metamethods...

Also, you can avoid the error doing this:

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

It is odd that you have tried to index a string using another string, however...

Luiz Menezes
  • 749
  • 7
  • 16