#479 simple option parser

Dubhead Wed 4 Mar 2009

Hi,

I have written a simple commandline option parser .

usage:

class OptParserTest: OptParser
{
    @optname=["b"]
    Bool myBool

    @optname=["i", "myint"]
    Int myInt := 42

    @optname=["f", "myfloat"]
    Float myFloat
}

class Main
{
    Void main(Str[] args) {
        optParseTest := OptParserTest()._parse(args)
        echo("myBool == " + optParseTest.myBool)
        echo("myInt == " + optParseTest.myInt)
        echo("myFloat == " + optParseTest.myFloat)
        echo("_args == " + optParseTest._args)
    }
}

output:

% fan optparse.fan -b --myfloat 13.37 -- foo bar
myBool == true
myInt == 42
myFloat == 13.37
_args == [foo, bar]

This is the first time I used reflection feature in any programming language, and it is fan! Hopefully some of you may find it useful.

JohnDG Wed 4 Mar 2009

You can simplify the interface to:

class OptParserTest: OptParser
{
    Bool myBool

    Int myInt := 42

    Float myFloat
}

Just use reflection to determine the slot name (and maybe toLowerCase it) and the slot type.

cheeser Wed 4 Mar 2009

Though, if i'm reading you right, that assumes that every field on the the object then would have a configuration flag which might not be what's wanted in every case. Thanks for writing this Dubhead. I had one kinda half done from some python porting I'd done a while back and had always intended to round it out. Now perhaps I won't have to.

Login or Signup to reply.