Skip to content

Instantly share code, notes, and snippets.

@inmatarian
Created April 12, 2016 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inmatarian/7fbe340bf2ae3160b6297d7c52d30060 to your computer and use it in GitHub Desktop.
Save inmatarian/7fbe340bf2ae3160b6297d7c52d30060 to your computer and use it in GitHub Desktop.
Minimal command line options parser (with tests)
-- Fast options parser
-- License: Public Domain
-- Can parse --arg=value types
-- Anything not --arg or --arg=value are positional types
-- Everything is a string, doesn't parse anything for you
-- OS/Host usually does the string split for you, so I don't bother.
-- Isn't POSIX compliant, because -arg and --arg and ---arg are treated the same.
function optparse(...)
local cfg = {}
for i = 1, select('#', ...) do
local arg = tostring((select(i, ...)))
local cmd, opt = arg:match('^%-+([A-Za-z0-9_]+)=([A-Za-z0-9_]+)$')
if cmd == nil then
cmd, opt = arg:match('^%-+([A-Za-z0-9_]+)$'), true
end
if cmd ~= nil then
cfg[cmd] = opt
else
cfg[#cfg+1] = arg
end
end
return cfg
end
it = {}
it["Detects '-opt'"] = function()
local cfg = optparse("-sup")
assert(cfg.sup == true)
end
it["Detects '--opt'"] = function()
local cfg = optparse("--sup")
assert(cfg.sup == true)
end
it["Detects '--opt=val'"] = function()
local cfg = optparse("--max_says=hi")
assert(cfg.max_says == 'hi')
end
it["Detects 'val1 val2'"] = function()
local cfg = optparse("val1", "val2")
assert(cfg[1] == 'val1' and cfg[2] == 'val2')
end
it["Detects mixed content"] = function()
local cfg = optparse('-sup', "val1", "--max_says=hi", "val2")
assert(cfg.sup == true)
assert(cfg.max_says == 'hi')
assert(cfg[1] == 'val1' and cfg[2] == 'val2')
end
for description, run in pairs(it) do
if xpcall(run, function(...)
print("FAILED:", description, '\n', (...), '\n', debug.traceback())
end) then
print("Passed:", description)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment