bzr branch
http://9ix.org/bzr/zoeplat
31
by Josh C
command line option for playback/record |
1 |
-- getopt_alt.lua |
2 |
||
3 |
-- getopt, POSIX style command line argument parser |
|
4 |
-- param arg contains the command line arguments in a standard table. |
|
5 |
-- param options is a string with the letters that expect string values. |
|
6 |
-- returns a table where associated keys are true, nil, or a string value. |
|
7 |
-- The following example styles are supported |
|
8 |
-- -a one ==> opts["a"]=="one" |
|
9 |
-- -bone ==> opts["b"]=="one" |
|
10 |
-- -c ==> opts["c"]==true |
|
11 |
-- --c=one ==> opts["c"]=="one" |
|
12 |
-- -cdaone ==> opts["c"]==true opts["d"]==true opts["a"]=="one" |
|
13 |
-- note POSIX demands the parser ends at the first non option |
|
14 |
-- this behavior isn't implemented. |
|
15 |
||
16 |
function getopt( arg, options ) |
|
17 |
local tab = {} |
|
18 |
for k, v in ipairs(arg) do |
|
19 |
if string.sub( v, 1, 2) == "--" then |
|
20 |
local x = string.find( v, "=", 1, true ) |
|
21 |
if x then tab[ string.sub( v, 3, x-1 ) ] = string.sub( v, x+1 ) |
|
22 |
else tab[ string.sub( v, 3 ) ] = true |
|
23 |
end |
|
24 |
elseif string.sub( v, 1, 1 ) == "-" then |
|
25 |
local y = 2 |
|
26 |
local l = string.len(v) |
|
27 |
local jopt |
|
28 |
while ( y <= l ) do |
|
29 |
jopt = string.sub( v, y, y ) |
|
30 |
if string.find( options, jopt, 1, true ) then |
|
31 |
if y < l then |
|
32 |
tab[ jopt ] = string.sub( v, y+1 ) |
|
33 |
y = l |
|
34 |
else |
|
35 |
tab[ jopt ] = arg[ k + 1 ] |
|
36 |
end |
|
37 |
else |
|
38 |
tab[ jopt ] = true |
|
39 |
end |
|
40 |
y = y + 1 |
|
41 |
end |
|
42 |
end |
|
43 |
end |
|
44 |
return tab |
|
45 |
end |