【问题标题】:How can I check type of multiple variables in one block?如何在一个块中检查多个变量的类型?
【发布时间】:2014-08-19 23:14:50
【问题描述】:

如何在一个if 语句块中检查多个变量的类型,而不使用多个if 语句?示例:

If var1 is not integer
{
    MsgBox, 0, Error, var1 is not integer
    Return
}
If var2 is not integer
{
    MsgBox, 0, Error, var2 is not integer
    Return
}

我想做的是检查单个布尔表达式中的类型。

我试过了,但它不起作用。

if ((var1 is not integer) or (var2 is not integer))
{
    MsgBox, 0, Error, variables are not integers
    Return
}

【问题讨论】:

  • 不应该是and,而不是or吗?
  • @RobertHarvey 或者在我的情况下是正确的。我正在检查两个不同的整数值(至少它们应该是)。如果其中任何一个都不是,我想终止脚本。请更新状态..到底有什么不清楚的地方?还需要什么其他信息?
  • 我以多种方式检查您的代码,但似乎那种 if 语句不允许使用括号 () 。所以我认为每个if 语句只能检查一个变量。此外,您可以使用嵌套的if 语句。
  • 我说or 是正确的!嵌套 if 语句的工作方式与 and 语句完全一样......天哪。

标签: autohotkey


【解决方案1】:

AHK 中的特殊 If 命令,如 If var [not] betweenIf var [not] in/contains MatchListIf var is [not] typeIfWin... 不是实际的布尔表达式,因此您不能链接 使用布尔运算符。
但是,这些条件语句可以包装在一个函数中。此外,If var is [not] type 可以使用 RegEx 重建:

方案一:包装函数

isInteger(arg) {
    if arg is integer
        return true
    else
        return false
}

if(isInteger(123) && isInteger(456)) {
    MsgBox, yay!
}

解决方案 2:正则表达式

if(RegExMatch(123, "^\d+$") && RegExMatch(456, "^\d+$")) {
    msgbox, hooray!
}

一些测试

如果您有兴趣,请查看数组值,复制脚本并运行它。你可能会发现一些令人惊讶的结果。我们的包装函数和RegExMatch 提供相同的背靠背结果。

arr := [123, 456, 123.456, "789", "not_an_integer!", true, false]
msg := ""
Loop % arr.MaxIndex()
{
    msg .= arr[A_Index]
    msg .= ":`tisInteger(): " isInteger(arr[A_Index])
    msg .= " RegExMatch(): " RegExMatch(arr[A_Index], "^\d+$")
    msg .= "`n"
}
msgbox  % msg


isInteger(arg) {
    if arg is integer
        return true
    else
        return false
}

【讨论】:

  • @JoeDF 你能详细说明一下吗?如果您的意思是某种类型的可变参数函数,我不知道 AHK 支持这种语法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-02
  • 2019-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-28
相关资源
最近更新 更多