Created
June 5, 2014 09:34
-
-
Save armornick/58376b78a2604c0f3cf5 to your computer and use it in GitHub Desktop.
Simple Argument Parser (and dependency-free pretty printer)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local concat, format = table.concat, string.format | |
------------------------------------------------------------------------- | |
--- Pretty Printing | |
------------------------------------------------------------------------- | |
function extended_tostring(o, qstring) | |
local otype = type(o) | |
if otype == "table" then | |
local result = {} | |
for k,v in pairs(o) do | |
result[#result+1] = format("%s = %s", extended_tostring(k), extended_tostring(v, true)) | |
end | |
return "{ "..concat(result, ", ").." }" | |
elseif otype == "string" and qstring then | |
return format("%q", o) | |
else | |
return tostring(o) | |
end | |
end | |
function pprint(v) | |
print(extended_tostring(v)) | |
end | |
function vpprint( ... ) | |
local args = {...} | |
for i = 1, #args do | |
print(extended_tostring(args[i])) | |
end | |
end | |
------------------------------------------------------------------------- | |
--- Argument Parsing | |
------------------------------------------------------------------------- | |
-- examples: | |
-- -a -b --compression=gzip /test alpha beta gamma | |
------------------------------------------------------------------------- | |
function argparse (argv) | |
local result = {} | |
for i = 1, #argv do | |
local argument = argv[i] | |
local parsedArg = argument:gsub("^%-+",""):gsub("^%/","") | |
if argument == parsedArg then | |
result[#result+1] = argument | |
else | |
local argkey, argval = parsedArg:match("(.-)=(.*)") | |
if argkey then | |
result[argkey] = argval | |
else | |
result[parsedArg] = true | |
end | |
end | |
end | |
return result | |
end | |
------------------------------------------------------------------------- | |
--- Main Application Entry | |
------------------------------------------------------------------------- | |
assert(arg) | |
pprint(argparse(arg)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment