1 -- --- T2-COPYRIGHT-NOTE-BEGIN ---
2 -- This copyright note is auto-generated by ./scripts/Create-CopyPatch.
4 -- T2 SDE: misc/lua/sde/getopt.lua
5 -- Copyright (C) 2005 - 2006 The T2 SDE Project
6 -- Copyright (C) 2005 - 2006 Juergen "George" Sawinski
8 -- More information can be found in the files COPYING and README.
10 -- This program is free software; you can redistribute it and/or modify
11 -- it under the terms of the GNU General Public License as published by
12 -- the Free Software Foundation; version 2 of the License. A copy of the
13 -- GNU General Public License can be found in the file COPYING.
14 -- --- T2-COPYRIGHT-NOTE-END ---
17 -- - add boolean option argument types
18 -- - maybe other types needed ?
21 -- opts,args,err = getopt(arg-list, option-definition)
22 -- Parses the "arg-list" according to "option-definition" and
23 -- returns the parsed options "opts", additional arguments "args" and
26 -- Option definition format:
27 -- key Option key (e.g. key = "help")
28 -- option String or list of options (e.g. option = {"-h", "--help"})
29 -- default Default value (e.g. default = false)
30 -- argument This option has no argument (ARG.none), a required
31 -- argument (ARG.required) or an optional argument (ARG.optional)
32 -- flag The option is flagged:
33 -- number (OPT.number)
34 -- incremental (OPT.incremental)
51 function getopt(args
,def
)
54 local nargs
= table.getn(args
)
56 -- first pass: defaults
57 for _
,d
in pairs(def
) do
58 if d
.default
~= nil then
59 opt
[d
.key
] = d
.default
63 -- Second pass: parse arguments
66 for _
,d
in pairs(def
) do
69 -- FIXME is there some shorter version for this:
70 if type(d
.option
) == "string" then
71 if d
.option
== args
[i
] then found
=true end
73 for k
=1,table.getn(d
.option
) do
74 if d
.option
[k
] == args
[i
] then
80 -- process option and arguments
83 local nextisopt
= false
86 -- check if next is an argument (not option)
87 if args
[i
+1] and string.sub(args
[i
+1],1,1) == "-" then
92 if nextisopt
and d
.argument
== ARG
.required
then
93 return nil, nil, "Missing option argument for `" .. args
[i
] .. "'"
97 (d
.argument
== ARG
.required
98 or d
.argument
== ARG
.optional
) then
109 if d
.flag
== OPT
.number then
111 elseif d
.flag
== OPT
.incremental
then
116 -- finally assign value
119 -- remove key from list (see third pass)
126 -- Third pass: check option, sort arguments
129 if string.sub(args
[i
],1,1) == "-" then
130 return nil, nil, "Unrecognized option `" .. args
[i
] .. "'"
132 table.insert(arg
, args
[i
])
144 opt
,arg
,err
= getopt(arg
, {
147 option
= { "-h", "-help", "--help" },
151 option
= { "-v", "-verbose", "--verbose" },
153 flag
= OPT
.incremental
164 for k
,v
in pairs(opt
) do
169 for k
,v
in pairs(arg
) do