getoptpair

function getoptpair( args [, name] ) --> opt, val, rest

Description

Parses an option pair. A pair has a option and a value and are conected via "=". For example:

--mode=safe

Parameters

args

The cli arguments that shoult be parsed.

name

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

Return Values

opt

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

val

The value of the option pair. If opt is nil is val also nil.

rest

The remaining entries from args.

Code

--ZFUNC-getoptpair-v1
local function getoptpair( args, name ) --> opt, val, rest
   if #args == 0 then
      return nil, nil, args
   end

   local pair = args[ 1 ]

   local i = string.find( pair, "=" )
   if not i then
      return nil, nil, args
   end

   local opt, val = string.sub( pair, 1, i-1 ), string.sub( pair, i+1 )
   if #opt == 0 or #val == 0 then
      return nil, nil, args
   end

   if name and opt ~= name then
      return nil, nil, args
   end

   local rest = {}
   for i = 2, #args do table.insert( rest, args[ i ] ) end

   return opt, val, rest
end

return getoptpair

Examples

local t = require( "tapered" )
local getoptpair = require( "getoptpair" )

args = { "--mode=safe", "-l" }

opt, val, rest = getoptpair( args )
t.is( opt, "--mode" )
t.is( val, "safe" )
t.same( rest, { "-l" } )

opt, val, rest = getoptpair( args, "--mode" )
t.is( opt, "--mode" )
t.is( val, "safe" )
t.same( rest, { "-l" } )

opt, val, rest = getoptpair( args, "--file" )
t.is( opt, nil )
t.is( val, nil )
t.same( rest, args )

t.done()

See also