getopts.lua 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. -- Interpret the parameters of a command, separating options and arguments.
  2. -- Input: command, param
  3. -- command: name of command
  4. -- param: parameters of command
  5. -- Returns: opts, args
  6. -- opts is a string of option letters, or false on error
  7. -- args is an array with the non-option arguments in order, or an error message
  8. -- Example: for this command line:
  9. -- /command a b -cd e f -g
  10. -- the function would receive:
  11. -- a b -cd e f -g
  12. -- and it would return:
  13. -- "cdg", {"a", "b", "e", "f"}
  14. -- Negative numbers are taken as arguments. Long options (--option) are
  15. -- currently rejected as reserved.
  16. function utility.getopts(command, param)
  17. local opts = ""
  18. local args = {}
  19. for match in param:gmatch("%S+") do
  20. if match:byte(1) == 45 then -- 45 = '-'
  21. local second = match:byte(2)
  22. if second == 45 then
  23. return false, "Invalid parameters (see /help " .. command .. ")."
  24. elseif second and (second < 48 or second > 57) then -- 48 = '0', 57 = '9'
  25. opts = opts .. match:sub(2)
  26. else
  27. -- numeric, add it to args
  28. args[#args + 1] = match
  29. end
  30. else
  31. args[#args + 1] = match
  32. end
  33. end
  34. return opts, args
  35. end