getoptvalues

function getoptvalues( args [, name [, max]] ) --> opt, values, rest

Description

Parses an option with the attendant values from an arguments table. For example:

--add 1 2 3

Parameters

args

The cli arguments that should be parsed.

name

An optional expected option name. The default name must just start with a "-".

max

The maximum number off values that are attendant to the option. The dafault behaviour if no max value is defined takes all entries that not start with "-".

Return Values

opt

The identified option value, or nil if the first value in args does not match name or does not start with "-".

values

The values that follow the opt entry in the args table. The maximal number of values can be defined with the max parameter. All entries that not start with "-". If the option value is nil is the values table empty.

rest

The remaining entries from args.

Code

--ZFUNC-getoptvalues-v1
local function getoptvalues( args, name, max ) --> opt, values, rest
   if #args == 0 then
      return nil, {}, args
   end

   if name and args[ 1 ] ~= name then
      return nil, {}, args
   end

   if string.sub( args[ 1 ], 1, 1 ) ~= "-" then
      return nil, {}, args
   end

   max = max or #args
   max = max+1
   if max > #args then
      max = #args
   end

   local opt = args[ 1 ]
   local values = {}
   local rest = {}
   for i = 2, #args do
      local val = args[ i ]
      if i <= max and
         #rest == 0 and
         string.sub( val, 1, 1 ) ~= "-" then
         table.insert( values, val )
      else
         table.insert( rest, val )
      end
   end

   return opt, values, rest
end

return getoptvalues

Example

local t = require( "taptest" )
local getoptvalues = require( "getoptvalues" )
local same = require( "same" )

args = { "--add", "1", "2", "3", "--sub", "3", "123" }

opt, values, rest = getoptvalues( args )
t( opt, "--add" )
t( same( values, { "1", "2", "3" } ), true )
t( same( rest, { "--sub", "3", "123" } ), true )

opt, values, rest = getoptvalues( args, "--add" )
t( opt, "--add" )
t( same( values, { "1", "2", "3" } ), true )
t( same( rest, { "--sub", "3", "123" } ), true )

opt, values, rest = getoptvalues( args, "--add", 1 )
t( opt, "--add" )
t( same( values, { "1" } ), true )
t( same( rest, { "2", "3", "--sub", "3", "123" } ), true )

opt, values, rest = getoptvalues( args, "--add", 2 )
t( opt, "--add" )
t( same( values, { "1", "2" } ), true )
t( same( rest, { "3", "--sub", "3", "123" } ), true )

opt, values, rest = getoptvalues( args, "--add", 5 )
t( opt, "--add" )
t( same( values, { "1", "2", "3" } ), true )
t( same( rest, { "--sub", "3", "123" } ), true )

opt, values, rest = getoptvalues( args, "--div" )
t( opt, nil )
t( #values, 0 )
t( args, rest )

opt, values, rest = getoptvalues( { "-a", "x", "y" }, "-a", 5 )
t( opt, "-a" )
t( same( values, { "x", "y" } ), true )
t( same( rest, {} ), true )

t()

See also