Advertisement
RodrickLord

Simple Argument Parser API

Apr 23rd, 2015
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.00 KB | None | 0 0
  1. --[[ Argument Parser API
  2.        By  RodrickLord
  3.  
  4. Code Example:
  5. Shell: "<program> --config1 --config2 true --config3 diamond"
  6.  
  7. args = api.parse(...)
  8.  
  9. args = {
  10.   config1 = true,
  11.   config2 = true,
  12.   config3 = "diamond",
  13. }
  14. ]]
  15.  
  16. l = string.lower
  17.  
  18. local function strTable(s)
  19.   local t = {}
  20.   for i in string.gmatch(s, "%s+") do
  21.     table.insert(t, i)
  22.   end
  23.   return t
  24. end
  25.  
  26. function parse(t,start)
  27.   local start = start or "--"
  28.   local r = {}
  29.   if type(t) == "string" then
  30.     t = strTable(t)
  31.   end
  32.   if type(t) == "table" then
  33.     for i = 1,#t do
  34.       if t[i]:sub(1,#start) == start then
  35.         if l(t[i+1]) == "true" or l(t[i+1]) == "t" or l(t[i+1]) == "yes" or l(t[i+1]) == "y" or t[i+1]:sub(1,#start) == start then
  36.           r[t[i]] = true
  37.         elseif l(t[i+1]) == "false" or l(t[i+1]) == "t" or l(t[i+1]) == "no" or l(t[i+1]) == "n" then
  38.           r[t[i]] = false
  39.         else
  40.           r[t[i]] = t[i+1]
  41.         end
  42.       end
  43.     end
  44.     return r
  45.   end
  46.   return false
  47. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement