Stata程序语法中是否存在以no开头的保留字?nosort选项异常
Stata程序中
nosort选项异常的问题 我编写了两个功能完全一致的Stata程序,仅可选选项名称不同,但运行表现却不一致:用hw作为选项名时程序正常响应,改用nosort时,即使带上选项运行,程序依然触发默认分支。我怀疑nosort是Stata的保留字,以下是测试代码:
clear all capture program drop my_test program define my_test syntax [, hw] if "`hw'" != "" dis "Hello world" if "`hw'" == "" dis "Am I insane?" end capture program drop my_test2 program define my_test2 syntax [, nosort] if "`nosort'" != "" dis "Hello world" if "`nosort'" == "" dis "Am I insane?" end my_test my_test, hw my_test2 my_test2, nosort
运行上述代码后得到结果:
. my_test Am I insane? . my_test, hw Hello world . . my_test2 Am I insane? . my_test2, nosort Am I insane?
问题原因
nosort并不是普通保留字,而是Statasyntax命令中的选项修饰符。当你在syntax语句里写, nosort时,Stata会将其解析为「不对输入的变量列表进行排序」的语法规则,而非定义一个名为nosort的用户选项。因此宏nosort永远不会被赋值,判断条件"``nosort'' != ""永远不成立,程序只会执行默认分支。
解决方法
如果坚持要使用类似名称作为选项,需要用双引号将选项名括起来,明确告诉Stata这是用户自定义选项:
capture program drop my_test2 program define my_test2 syntax [, "nosort"] if "`nosort'" != "" dis "Hello world" if "`nosort'" == "" dis "Am I insane?" end
修改后再运行my_test2, nosort,就能正常输出"Hello world"。更简单的方式是直接更换选项名(比如nosort_opt),避免和Stata的语法修饰符冲突。
内容的提问来源于stack exchange,提问作者Moritz Poll
相关产品推荐
相关产品推荐

