Simplified getopt for lua
Lua doesn’t include getopt. I have written this very simple implementation. It is actually a simplified version of AlternativeGetOpt. It is usable but absolutely not user-proof! Good enough for your own scripts though.
function getopt(o) local p = {} for k,v in ipairs(arg) do if v:byte(1) == 45 then local l = v:sub(2,2) if o:match(l) then p[l] = arg[k+1] else p[l] = true end end end return p end
You can test for example with the following main function:
function main() local opts = getopt("up") local user = opts.u and opts.u or "default" local pass = opts.p and opts.p or "secret" local root = opts.a and true or false print(user, pass, root) end
Usage examples:
$ getopt default secret false $ getopt -u lyderic lyderic secret false $ getopt -u lyderic -p password lyderic password false $ getopt -a -u lyderic -p password lyderic password true $ getopt -a -u lyderic -w lyderic secret true
The full code is on github: https://github.com/lyderic/scripts/blob/master/getopt.lua