• Options in linux

    From none) (albert@21:1/5 to All on Wed Mar 8 14:08:14 2023
    It is often times useful to pass options to a turnkey program.
    The following may save people to reinvent the wheel.

    Note:
    $@ is known by @+ analogous to COUNT (C@+).
    ARGS is passed to a program, the arguments and the environment.

    ( ARGC ARGV ARG[] SHIFT-ARGS ENV ) \ AvdH B2sep21
    \ For a CSTRING (pointer to zero ended chars) return a STRING.
    : Z$@ DUP BEGIN COUNT 0= UNTIL 1- OVER - ;
    \ Return the NUMBER of arguments passed by Linux
    : ARGC ARGS @ @ ;
    \ Return the argument VECTOR passed by Linux
    : ARGV ARGS @ CELL+ ;
    \ Return the environment POINTER passed by Linux
    : ENV ARGS @ $@ 1+ CELLS + ;
    \ Find argument INDEX, counting from one. Return as a STRING.
    : ARG[] CELLS ARGV + @ Z$@ ;
    \ Return POINTER behind the end-0 of the environment.
    : ENV0 ENV BEGIN $@ WHILE REPEAT ;
    \ Shift the arguments, so as to remove argument 1.
    : SHIFT-ARGS ARGV >R
    R@ CELL+ CELL+ R@ CELL+ ENV0 R> - MOVE
    -1 ARGS @ +! ;
    ---------------------
    : handle-options BEGIN ARGC 1 > DUP IF 1 ARG[] DROP C@ &- = THEN
    WHILE 1 ARG[] EVALUATE REPEAT ;

    Example of how to use options. Note how we take advantage of
    Forth being an interpreter. The first SHIFT-ARGS get rid of the
    option. The second SHIFT-ARGS get rid of the parameter.
    EVALUATE calculates an address. The minimum search order is most
    appropriate to this. In ciforth this is e.g.
    ONLY EVALUATE PREVIOUS

    \ Execute option -p : set the parallel port address.
    : -p SHIFT-ARGS 1 ARG[] HEX EVALUATE ATTACH-PARALLEL-PORT DECIMAL
    SHIFT-ARGS ;
    \ Execute option -s : set the serial device name.
    : -s SHIFT-ARGS 1 ARG[] serial-device$ $! SHIFT-ARGS ;
    --
    Don't praise the day before the evening. One swallow doesn't make spring.
    You must not say "hey" before you have crossed the bridge. Don't sell the
    hide of the bear until you shot it. Better one bird in the hand than ten in
    the air. First gain is a cat spinning. - the Wise from Antrim -

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)