简体   繁体   English

为什么我的循环不在 function 内触发?

[英]Why doesn't my loop trigger inside a function?

I'm just trying to perform a very simple for loop in a function and yet it's not working as expected.我只是想在 function 中执行一个非常简单的 for 循环,但它没有按预期工作。 However, If I replace the checkForImage() call with the contents of the function, it works.但是,如果我用 function 的内容替换 checkForImage() 调用,它就可以工作。 Is there something wrong with my syntax?我的语法有问题吗?

dict := {"img1": "shark","img2": "blue","img3": "red"}

sendAnswers(answer) {
  msgbox, %answer%
}

checkForImage() {
    MsgBox hi
    for key, val in dict
     MsgBox %val%
    return
}

^z::
   checkForImage()

I get a message box with "hi" but the loop doesn't seem to do anything.我收到一个带有“hi”的消息框,但循环似乎没有做任何事情。

I am using Version 1.1.30.00我正在使用版本 1.1.30.00

Your syntax is correct.你的语法是正确的。 The function simply cannot "see" dict . function 根本无法“看到” dict There are a couple of ways to solve this problem, see Global .有几种方法可以解决这个问题,请参阅Global

First method: Only dict is global, all other variables are accessible only within checkForImage() .第一种方法:只有dict是全局的,所有其他变量只能在checkForImage()中访问。 If you're accessing only dict or a couple more global variables, this method is recommended.如果您只访问dict或几个全局变量,建议使用此方法。

checkForImage() {
    global dict ; Only dict will be global (accessible outside this function)
    myLocalVariable := 0 ; This is accessible only within this function

    MsgBox hi
    for key, val in dict
        MsgBox %val%
}

Second method: ALL variables within the function is global.第二种方法:function内的ALL变量是全局的。

checkForImage() {
    Global  ; dict and all other global variables will be accessible

    myNotLocalVariable := 0 ; This is accessible even outside this function
    MsgBox hi
    for key, val in dict
     MsgBox %val%
    return
}

Third method: Declare dict as a super-global variable.第三种方法:将dict声明为超全局变量。

global dict := {"img1": "shark","img2": "blue","img3": "red"}
checkForImage() {
    MsgBox hi
    for key, val in dict
     MsgBox %val%
    return
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM