0

我正在使用一个名为 .ado 的文件flow。如果用户键入flow i我希望if运行一条语句。如果用户键入flow e,我希望if运行另一条语句。

我该怎么做呢?

4

3 回答 3

3

本论坛的许多读者都希望看到您尝试过的一些代码......

program flow 
    version 8  // will work on almost all Stata in current use 
    gettoken what garbage : 0 
    if "`what'" == "" | "`garbage'" != "" | !inlist("`what'", "e", "i")  { 
       di as err "syntax is flow e or flow i"
       exit 198 
    }

    if "`what'" == "e" { 
       <code for e>
    }
    else if "`what'" == "i" { 
       <code for i>
    } 
end 

最后一个if条件是多余的,因为我们已经确定用户输入了eor i。根据口味编辑。

于 2013-10-25T09:31:00.857 回答
2

鉴于您对@NickCox 的回答的评论,我假设您尝试过这样的事情:

program flow
    version 8
    syntax [, i e]
    if "`i'`e'" == "" {
        di as err "either the i or the e option needs to be specified"
        exit 198
    }
    if "`i'" != "" & "`e'" != "" {
        di as err "the i and e options cannot be specified together"
        exit 198
    }
    if "`e'" != "" {
        <code for e>
    }
    if "`i'" != "" {
        <code for i>
    }
end

之后你flow像这样调用:flow, iflow, e。注意逗号,这现在是必需的(但不是在@NickCox 的命令中),因为您为它们设置了选项。

于 2013-10-25T10:42:27.650 回答
1

如果您想要ie成为互斥选项,那么这是另一种选择:

 program flow
    version 8
    capture syntax , e 

    if _rc == 0  { // syntax matched what was typed 
        <code for e>
    }
    else {
        syntax , i // error message and program exit if syntax is incorrect
        <code for i>
    }
end

如果每个分支中的代码都很长,那么出于良好的风格,许多人会更喜欢每种情况的子程序,但这与这里的草图是一致的。请注意,在每个syntax语句中,该选项都被声明为强制性的。

的效果capture是这样的:错误不是致命的,而是被capture. 所以你需要查看返回码,可以在_rc. 0_rc始终表示命令成功。非零总是意味着命令不成功。在这里,通常在其他地方,命令只有两种方式是正确的,所以我们不需要知道什么_rc是正确的;我们只需要检查其他合法语法。

请注意,即使我在这里的两个答案在用户键入非法命令时是否收到信息性错误消息或只是“无效语法”的风格上也有所不同。上下文是期望每个 Stata 命令都附带一个帮助文件。一些程序员假设帮助文件解释了语法。其他人希望他们的错误消息尽可能有用。

于 2013-10-25T12:43:16.343 回答