parsecmdline_pk.lua (2004B)
1 2 local pairs = pairs 3 4 -- Get options from command line. 5 -- 6 -- opts, args = getopts(opt_meta, arg, usage_func) 7 -- 8 -- <opts>: table { [optletter]=true/false/string/tab } 9 -- <args>: string sequence 10 -- 11 -- <opt_meta>: Meta-information about options, table of [optletter]=<info>, 12 -- false: doesn't have argument (i.e. is switch) 13 -- true: has argument, collect once 14 -- 1: has argument, collect all 15 -- opt_meta[0] is an offset for the indices of the returned <args> table. For 16 -- example, if it's -1, the args[0] will be the first positional argument. 17 -- 18 -- <arg>: The arguments provided to the program 19 -- <usage_func>: Function to print usage and terminate. Should accept optional 20 -- prefix line. 21 local function getopts(opt_meta, arg, usage) 22 local opts = {} 23 for k,v in pairs(opt_meta) do 24 -- Init tables for collect-multi options. 25 if (v and v~=true) then 26 opts[k] = {} 27 end 28 end 29 30 -- The extracted positional arguments: 31 local args = {} 32 local apos = 1 + (opt_meta[0] or 0) 33 34 local skipnext = false 35 local proc = true 36 for i=1,#arg do 37 if (skipnext) then 38 skipnext = false 39 goto next 40 end 41 42 if arg[i] == "--" then proc = false end 43 if (proc and arg[i]:sub(1,1)=="-") then 44 local opt = arg[i]:sub(2) 45 skipnext = opt_meta[opt] 46 if (skipnext == nil) then 47 usage("Unrecognized option "..arg[i]) 48 elseif (skipnext) then 49 if (arg[i+1] == nil) then 50 usage() 51 end 52 if (skipnext~=true) then 53 opts[opt][#opts[opt]+1] = arg[i+1] 54 else 55 opts[opt] = arg[i+1] 56 end 57 else 58 opts[opt] = true 59 end 60 else 61 proc = false 62 args[apos] = arg[i] 63 apos = apos+1 64 end 65 ::next:: 66 end 67 68 return opts, args 69 end 70 71 return { 72 getopts = getopts 73 }