Frank
Frank

Reputation: 574

Why does the `syntax` command get weird with string variables in Stata?

Let's say I make the following simple program:

program define test_prog1
    syntax varname =exp
    display `"`varlist' `exp'"'
end

And I run it with the following commands in the Stata interpreter, where I already have variables in the workspace:

. gen a=_n
. tostring a, replace
a was float, now str6
. test_prog1 a="aaa"
type mismatch

What? It's a variable followed by an expression, what type is there to mismatch when I didn't specify a type in my syntax command? And even if I do specify varname(string) or varname(str#) it doesn't help--and even if it did, for the real program I'm trying to write I want to work regardless of whether varname is string or numeric.

How do I get my program to accept either numeric or string variables in varname, and not blow up when it's given a ="string_constant" expression?

Upvotes: 0

Views: 101

Answers (1)

dimitriy
dimitriy

Reputation: 9460

The pdf manual says exp must be numeric:

enter image description here

I am not sure if there is a way to shoehorn this into syntax or args, but this would get you close:

set obs 3
gen a =_n
tostring a, gen(b)

capture program drop test_prog1    
program define test_prog1
    gettoken varname rest : 0, parse(" =")
    confirm variable `varname'
    display `"`varname'"'
    display `"`rest'"'  
end

test_prog1 a=3
test_prog1 b="3"
test_prog1 c =4

Upvotes: 2

Related Questions