Announcement

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

  • Using "*" in -syntax- leads to unexpected lack of syntax checks

    Hi Statalist. I just noticed an unexpected downside of "*" in -syntax- when writing programs. Consider this example

    Code:
    program define mytest  
      syntax, [norm(integer -1 ) *]  
      di "`norm'"  
      di "`options'"
    end
    
    mytest, norm(-1)  
    mytest, norm(abc)
    Because of the * in the syntax, Stata is not returning an invalid syntax error for mytest, norm(abc) even though it is not the right syntax because norm should be a string.
    Instead, it is using the default value for norm and passing the incorrectly-syntaxed norm(abc) option as an extra option in `options`.

    This means that Stata is not properly checking for syntax errors if the "*" option is used.

    Is this expected behavior? How can I modify the program above so it checks syntax while retaining the functionality of passing additional options?

    Thank you,
    Jorge Eduardo Pérez Pérez
    www.jorgeperezperez.com

  • #2
    As far as I understand, the behavior is intended. Look at it this way: You can either allow any additional options or have those options raise a syntax error. You cannot have both at the same time.

    Here is one way you could check for invalid input while allowing additional options

    Code:
    program define mytest
        
        syntax [ , NORM(integer -1) NORM2(passthru) * ]
        
        if (`"`norm2'"' != "") {
            
            display as err "option norm() incorrectly specified"
            exit 198
            
        }
        
    end
    Last edited by daniel klein; 13 May 2024, 16:04. Reason: slightly rephrased

    Comment


    • #3
      Here is an even better way to do what you want:

      Code:
      program define mytest
          
          syntax [ , NORM(numlist integer max=1) * ]
          
          if ("`norm'" == "") local norm -1
          
      end
      Because numlist does not define a default, Stata checks for valid input. You supply the default value in a second step.

      Comment


      • #4
        Thank you daniel klein . The second example you posted is exactly what I'm looking for.




        Jorge Eduardo Pérez Pérez
        www.jorgeperezperez.com

        Comment

        Working...
        X