Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Is it possible to not set values of optional integer arguments with the syntax command

    When specifying optional arguments integer arguments using the syntax command it is usually necessary to set a value. Is it possible to get round this feature?

    For example I am writing a program where an argument is optional as long as option1 hasn't also been given. If option1 has been given I want the program to produce an error if the argument has not been given.

    A work around is to set the value to one that would be implausible for the user to enter but this does not seem ideal. Is there a better way to do this?

    Code:
    prog define foo
        syntax, [option1, a_number(integer -99999)]
        if `a_number' == -99999 & "`option1'" != "" {
            di as error "a_number must be provided if option1 is specified"
        }
    end

  • #2
    I would not use so-called magical numbers. You could either use a two-step approach

    Code:
    program foo
        version 15
        
        syntax [ , option1 * ]
        
        if ("`option1'" != "") syntax , option1 a_number(integer)
        else local a_number 42 // default
    
        ...
    end
    or use an optional numlist.


    Code:
    program bar
        version 15
        
        syntax [ , option1 a_number(numlist integer max=1) ]
        
        if ("`option1'" != "") {
            if ( mi("`a_number'") ) {
                display as err "a_number must be provided ..."
                exit 198
            }
        }
        else local a_number 42 // default
        
        ...
    end
    In both cases, you will have to set a default value yourself.

    Edit: The numlist approach has the advantage that you can easily include checks for acceptable integer values in the syntax command.

    btw. I avoid using underscores or numbers in option names; those do not work well with the uppercase abbreviations used for options.

    Best
    Daniel
    Last edited by daniel klein; 31 Oct 2019, 08:49.

    Comment


    • #3
      I often document in the help that two options are incompatible and then trap a call to both.


      Code:
      syntax [, option1 option2(arguments) ] 
      
      
      if "`option1'" != "" & "`option2'" != "" { 
          di as err "option1 and option2() may not be specified together"
          exit 198 
      }

      Comment


      • #4
        Thanks Nick and Daniel for your responses. Very helpful. Magical numbers did not seem to be a good way to go.

        Comment

        Working...
        X