Advertisement
Wobbo

oc-getopt

Jan 26th, 2014
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.61 KB | None | 0 0
  1. --- Module for POSIX getopt
  2. -- @author Wobbo
  3.  
  4. --- Iterate over all the options the user provided.
  5. -- This function returns an iterator that can be used in the generic for that iterates over all the options the user specified when he called the program. It takes the arguments that were provided to the program, and a list of valid options as a string.
  6. -- @tparam table args A table with the command line options provided
  7. -- @tparam string options A string with all the valid options
  8. function getopt(args, options)
  9.   checkArg(1, args, "table")
  10.   checkArg(2, options, "string")
  11.   local current = nil
  12.   local pos = 1
  13.   return function()
  14.     if #args <= 0 then
  15.       return nil -- No arguments left to process
  16.     end
  17.     if not current or #current < pos then
  18.       if string.find(args[1], "^%-%w") then
  19.         current = string.sub(args[1], 2, #args[1])
  20.         pos = 1
  21.         table.remove(args, 1)
  22.       else
  23.         return nil -- No options left to process, the rest is up to the program
  24.       end
  25.     end
  26.     local char = current:sub(pos, pos)
  27.     pos = pos +1
  28.     if char == '-' then
  29.       return nil -- Stop processing by demand of user
  30.     end
  31.     local i, j = string.find(options, char..':*')
  32.     if not i then
  33.       return '?', char
  34.     elseif j-i == 0 then
  35.       return char
  36.     elseif j - i == 1 then
  37.       if not args[1] or args[1]:sub(1,1) == '-' then
  38.         return ':', char
  39.       else
  40.         return char, table.remove(args, 1)
  41.       end
  42.     elseif j - i == 2 then
  43.       return char, (args[1] and args[1]:sub(1,1) ~= '-' and table.remove(args, 1)) or nil
  44.     end
  45.   end
  46. end
  47.  
  48. return getopt
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement