String argument with optional value in std.getopt

Steven Schveighoffer schveiguy at gmail.com
Sun Aug 9 12:20:16 UTC 2020


On 8/8/20 7:58 PM, Hassan wrote:
> Hello
> 
> I'm trying to get getopt to recognize an argument that may or may not 
> take a value. Here's an example :
> 
> ../hashtrack --list
> ../hashtrack --list filter
> 
> The problem is that if I point list to a string variable, the first call 
> fails with "Missing value for argument --list".
> 
> I tried having it point to a callback with an optional second parameter :
> 
> void cb(string option, string value = "")
> {
>      writeln("--list");
>      option.writeln();
>      value.writeln();
> }
> 
> But I get the same error. I also tried having two callbacks with the 
> same name. The first one takes a single argument, and the second one 
> accepts two :
> 
> void cb(string option)
> {
>      writeln("--list");
>      option.writeln();
> }
> 
> void cb(string option, string value)
> {
>      writeln("--list");
>      option.writeln();
>      value.writeln();
> }
> 
> But it only calls the first one. I'm using DMD64 D Compiler v2.090.0. 
> Any pointers ?

getopt doesn't support optional parameters.

Two things I can think of:

1. Have 2 options that do the same thing, but only one accepts a 
parameter (e.g. `--list` and `--listf filter`)
2. If your optional parameters are not tied to the option itself, then 
don't accept them via getopt. In other words, if `hashtrack filter` is 
supposed to be valid, then filter isn't an option after all, it's a 
standard parameter.

-Steve


More information about the Digitalmars-d-learn mailing list