[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: GetOpt
- From: "Inmate 2993" <inmatarian@...>
- Date: Thu, 3 May 2007 18:41:29 -0400
Hows this look? I had to write my own getopt while writing a posix compliant version of cat, and, I didn't like the versions of getopt that others have written. It works for my purposes, but I'd like to hear thoughts and where I'm breaking posix compliance.
-- getopt returns a table where associated keys are true or nil
-- the string options contains the options that have associated values `-b one' style
-- Example: opts["a"]==true, opts["b"]=="one"
function getopt( arg, options )
local tab = {}
local count = 1
for k, v in ipairs(arg) do
if ( string.sub( v, 1, 2) == "--" ) then
local x = string.find( v, "=", 1, true )
if ( x ) then tab[ string.sub( v, 3, x-1 ) ] = string.sub( v, x+1 )
else tab[ string.sub( v, 3 ) ] = true
end
elseif ( string.sub( v, 1, 1 ) == "-" ) then
local y = 2
local k
while ( y <= string.len(v) ) do
k = string.sub( v, y, y )
if ( string.find( options, k, 1, true ) ) then
repeat
if string.sub( arg[count], 1, 1) ~= "-" then
tab[ k ] = arg[count]
break
end
count = count + 1
if ( count > #arg ) then tab[ k ] = true end
until count > #arg
else tab[ k ] = true
end
y = y + 1
end
end
end
return tab
end