难以理解检索传递给函数中脚本的参数值的机制

时间:2012-11-13 20:53:35

标签: syntax autohotkey

脚本将两个参数值传递给脚本的另一个实例。因此内置参数变量0包含传递的参数数量。 1在下面的例子中是“C:/ Windows”,2是“/ switchtest”

可以使用函数外部的传统方法(使用单个等号)将参数值分配给strParam1和strParam2。但是,在函数内部,分配失败。

如果它们在带有= =符号的循环中分配,它似乎有效。

为什么?任何人都可以解释这种行为吗?

strParam1 = %1%
strParam2 = %2%
msgbox, 64, Outside the Function, number of parameters:%0%`npath: %strParam1%`nswitch: %strParam2%
test_params()


strPath := "C:/Windows"
strSwitch := "/switchtest"
RunWait "%A_AhkPath%" "%A_ScriptFullPath%" "%strPath%" "%strSwitch%"


test_params() {
    global 0

    ; this works
    ; loop %0%
        ; strParam%A_Index% := %A_Index%

    ; this causes an error: "This dynamic variable is blank. If this variable was not intended to be dynamic, remove the % symbols from it."
    ; strParam1 := %1%
    ; strParam2 := %2%

    ; this passes empty values; however, this method works outside the function.
    strParam1 = %1%
    strParam2 = %2%

    msgbox, 64, Inside the Function, number of parameters:%0%`npath: %strParam1%`nswitch: %strParam2%
    if strParam2
        exitapp

}

2 个答案:

答案 0 :(得分:1)

你对global 0有正确的想法;允许%0%从顶层进入函数。您只需要声明global 1, 2

即使你这样做,也不能使用:=将它们分配给变量,因为:=处理表达式,并且没有语法在表达式中使用它们(通常引用变量)在仅包含变量名称的表达式中,没有%%;显然12被解释为实际数字而不是变量。“

答案 1 :(得分:0)

@echristopherson回答了这个问题,但我想提出一个解决方法。这假设您正在使用AutoHotkey_L。

如果你使用args“a b c”运行测试脚本,它会给你这个。

3
1, a
2, b
3, c

测试:

argv := args()
test := argv.MaxIndex() "`n"

for index,param in argv
    test .= index ", " param "`n"

MsgBox % test

功能:

args() {
    global
    local _tmp, _out

    _out := []

    Loop %0% {
        _tmp := %A_Index%
        if _tmp
            _out.Insert(_tmp)
    }

    return _out
}