[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: How to getopt?
- From: Axel Kittenberger <axkibe@...>
- Date: Thu, 23 Dec 2010 12:28:58 +0100
When called by the lua standalone, the arguments are stored in "arg".
IMHO a "high order" language like lua does not need a getopt library,
as this is pretty easy to do yourself, and you do not need additional
requirements.
This for example is a simplified case of my use, searches for all
options starting with a "-", it does not care about short opts, there
are long opts only. and all options not part of a "-" is stored in
"nonopts" for later parsing.
-- first argument if number of arguments the option takes, second the
function to handle them.
local options = {
logfile = {1, function(file) settings.logfile = file end},
nodaemon = {0, function() settings.nodaemon=true end},
-- etc.
}
-- nonopts is filled with all args that were no part dash options
local nonopts = {}
local i = 1
while i <= #arg do
local a = args[i]
if a:sub(1, 1) ~= "-" then
table.insert(nonopts, args[i])
else
if a:sub(1, 2) == "--" then
a = a:sub(3)
else
a = a:sub(2)
end
local o = options[a]
if not o then
print("unknown option command line option: ", a)
os.exit(-1)
end
if o[1] >= 0 and i + o[1] > #args then
print"Error",a," needs ",o[1]," arguments")
os.exit(-1)
end
-- this is a bit dirty, I have no more than 3 args ever, and was too
lazy to think of general code.
-- a more generic solution would build a list and call the function
with unpack(list)
if o[2] then
if o[1] == 0 then
o[2]()
elseif o[1] == 1 then
o[2](args[i + 1])
elseif o[1] == 2 then
o[2](args[i + 1], args[i + 2])
elseif o[1] == 3 then
o[2](args[i + 1], args[i + 2], args[i + 3])
end
end
i = i + o[1]
end
i = i + 1
end
--- care about your nonopts here
On Thu, Dec 23, 2010 at 1:49 AM, Steve Litt <slitt@troubleshooters.com> wrote:
> Hi all,
>
> I'm rewriting my UMENU program
> (http://www.troubleshooters.com/umenu/index.htm) in Lua, and so far so good.
> So far, I see little reason to ever use Perl again :-)
>
> UMENU uses Perl's getopt_long. I've read all sorts of things about Lua's
> Getopt facility, and so far it seems like yes, there's one in the standard
> package, but some are saying it doesn't work all that well and a lot of people
> are writing their own getopt facilities.
>
> Ideally, I'd like my Lua based UMENU to work with plain, ordinary, everyone
> can install it Lua, rather than depending on special packages the user needs
> to install, so if the one in the standard library works, that's what I'd like
> to use. I could also just manually check for arguments -- there aren't that
> many options to UMENU.
>
> So what are you all using for Getopt or preferably Getopt_long in Lua?
>
> Thanks
>
> SteveT
>
> Steve Litt
> Recession Relief Package
> http://www.recession-relief.US
> Twitter: http://www.twitter.com/stevelitt
>
>
>