Advertisement
ecoMeco

getopt

Aug 12th, 2016
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.84 KB | None | 0 0
  1. --CC Getopt-- by Admicos (os.loadAPI edition)
  2.  
  3. -- nil getopt.help(string programDescription, table optionsTable) !INTERNAL!
  4. function help(name, desc, options)
  5.     local helpStr = name .. " -- " .. desc .. "\n"
  6.     .. "USAGE: " .. name .. " [options] [args]\n"
  7.  
  8.     for k, v in pairs(options) do
  9.         helpStr = helpStr .. "\n--" .. k .. " (-" .. v[2] .. ")"
  10.         if v[3] ~= nil then
  11.             helpStr = helpStr .. " [" .. v[3] .. "]"
  12.         end
  13.         helpStr = helpStr .. ": " .. v[1]
  14.     end
  15.  
  16.     textutils.pagedPrint(helpStr)
  17. end
  18.  
  19. -- table or nil getopt.init(string name, string programDescription, table optionsTable, table args)
  20. -- NOTE: In optionsTable, you can't have --help or -h because getopt creates them for you.
  21. function init(name, desc, options, args)
  22.     local _resTbl = {}
  23.     local _isArg = false
  24.     local _optCnt = 1
  25.  
  26.     for i, v in ipairs(args) do
  27.         if v == "-h" or v == "--help" then
  28.             _resTbl = {}
  29.             getopt.help(name, desc, options)
  30.  
  31.             return nil
  32.         end
  33.  
  34.         if v:sub(1, 1) == "-" then
  35.             for j, x in pairs(options) do
  36.                 if v == "--" .. j or v == "-" .. x[2] then
  37.                     if x[3] ~= nil then
  38.                         _resTbl[j] = args[i + 1]
  39.                         _isArg = true
  40.                     else
  41.                         _resTbl[j] = true
  42.                     end
  43.                 end
  44.             end
  45.         elseif not _isArg then
  46.             _resTbl["opt-" .. _optCnt] = v
  47.             _optCnt = _optCnt + 1
  48.         else
  49.             _isArg = false
  50.         end
  51.     end
  52.  
  53.     return _resTbl
  54. end
  55.  
  56. -- Example Program:
  57.  
  58. -- os.loadAPI("getopt")
  59. -- local _optionsExample = {
  60. --  ["color"] = {"Should it be colored", "c", nil},
  61. --  ["number"] = {"How many times should it print", "n", "num"},
  62. -- }
  63. --
  64. -- local tbl = getopt.init("Prints text with color", _optionsExample, { ... })
  65. --
  66. -- if tbl ~= nil then
  67. --  if tbl["color"] then term.setTextColor(colors.orange) end
  68. --  for i = 1, tonumber(tbl["number"]) do
  69. --      print(tbl["opt-1"])
  70. --  end
  71. -- end
  72.  
  73. --Valid example arguments: --number 5 -c hello world
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement