mpeterv / argparse

Feature-rich command line parser for Lua
MIT License
251 stars 43 forks source link

How to stop handling options after an argument? #23

Closed edubart closed 5 years ago

edubart commented 5 years ago

I am unable to stop handling option parsing after some argument. This is useful for creating scripts that need to pass arguments when invoking shell commands. For example this sample code does not work as intended:

local argparser = require'argparse'()
argparser:flag('-s --something', "Something flag")
argparser:argument("input", "Input"):action(function()
  argparser:handle_options(false)
end)
argparser:argument("args"):args("*"):action('concat')
local options = argparser:parse()
print(table.concat(options.args, ' '))

When running with lua test.lua -s file a1 a2 -c:

Usage: playground/playground.lua [-s] [-h] <input> [<args>] ...

Error: unknown option '-c'
Did you mean one of these: '-h' '-s'?

What I would expect is when input is consumed the argparser:handle_options(false) would cancel argparser to handle options and the above example would outputs a1 a2 -c.

daurnimator commented 5 years ago

@edubart did you get a solution for this?

p-ouellette commented 5 years ago

It's not possible to disable option handling after parsing has started. You could use lua test.lua -s file -- a1 a2 -c instead.

edubart commented 5 years ago

@daurnimator I made a "hack" by injecting -- into the args just after parsing the first input argument. Not a pretty solution, but worked for me, the code can be seen here:

https://github.com/edubart/euluna-lang/blob/master/euluna/configer.lua#L38