Advertisement
ecoMeco

getopt

Aug 12th, 2016
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.30 KB | None | 0 0
  1. --pp:ifndef INCL_GETOPT
  2. --pp:define INCL_GETOPT
  3. local getopt = {}
  4.  
  5. function getopt.help(name, desc, options)
  6.     local helpStr = name .. " -- " .. desc .. "\n"
  7.     .. "USAGE: " .. name .. " [options] [args]\n"
  8.  
  9.     for k, v in pairs(options) do
  10.         helpStr = helpStr .. "\n--" .. k .. " (-" .. v[2] .. ")"
  11.         if v[3] ~= nil then
  12.             helpStr = helpStr .. " [" .. v[3] .. "]"
  13.         end
  14.         helpStr = helpStr .. ": " .. v[1]
  15.     end
  16.  
  17.     textutils.pagedPrint(helpStr)
  18. end
  19.  
  20. -- table or nil getopt.init(string programDescription, table optionsTable, table args)
  21. -- NOTE: In optionsTable, you can't have --help or -h because getopt creates them for you.
  22. function getopt.init(name, desc, options, args)
  23.     local _resTbl = {}
  24.     local _isArg = false
  25.     local _optCnt = 1
  26.  
  27.     for i, v in ipairs(args) do
  28.         if v == "-h" or v == "--help" then
  29.             _resTbl = {}
  30.             getopt.help(name, desc, options)
  31.  
  32.             return nil
  33.         end
  34.  
  35.         if v:sub(1, 1) == "-" then
  36.             for j, x in pairs(options) do
  37.                 if v == "--" .. j or v == "-" .. x[2] then
  38.                     if x[3] ~= nil then
  39.                         _resTbl[j] = args[i + 1]
  40.                         _isArg = true
  41.                     else
  42.                         _resTbl[j] = true
  43.                     end
  44.                 end
  45.             end
  46.         elseif not _isArg then
  47.             _resTbl["opt-" .. _optCnt] = v
  48.             _optCnt = _optCnt + 1
  49.         else
  50.             _isArg = false
  51.         end
  52.     end
  53.  
  54.     return _resTbl
  55. end
  56. --pp:ignoreend
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement