How do I access global variables in local scope without “possibly used before declaration” -errors?

青春壹個敷衍的年華 提交于 2021-01-28 01:42:45

问题


I'm getting this warning: WARNING: $a possibly used before declaration. for my function:

Func test()
    If (IsDeclared("a")) Then
        ConsoleWrite($a)
    Else
        ConsoleWrite("Not declared")
    EndIf
EndFunc

Global $a = "test"

test()

Can be avoided by using the global variable as a parameter to the function. But I need this construct because it's tied to a file-operation which I don't want to execute every time I need the variable.

How can I do this without generating a "possibly used before declaration" -error?


回答1:


Firstly, this warning is reported by Au3Check.exe, a program that is separate from the AutoIt compiler itself. You'll find that your program will still compile/run after this warning is printed. One possible solution is to just ignore it, or not run Au3Check on your code (not recommended).

Your code will work fine if you simply defined your functions at the end. You were probably already aware of this, and I know when you #include functions they will likely be at the top.

Another possible solution if it really is annoying you is to use Eval. I don't recommend this as it's not needed and breaks your script if using Au3Stripper (used to be obfuscator) though your code is already broken by the use of IsDeclared.

A solution (probably the best solution) you probably wouldn't have thought of is using Dim for this.

Func test()
    If(IsDeclared("a")) Then
        Dim $a

        ConsoleWrite($a & @LF)
    Else
        ConsoleWrite("Not declared" & @LF)
    EndIf
EndFunc

Global $a = "test"

test()

Basically, Dim acts like Local, unless a variable with that name already exists in the global scope, in which case it is reused.




回答2:


I'm getting this warning: WARNING: $a possibly used before declaration.

AU3Check determined a variable being accessed prior to its declaration (by order of code). It's unaware the containing function is not called prior to variable's declaration, hence produces a warning (rather than reporting an error).

Declaring concerning function after declaration of global variable it is to access prevents AU3Check's warning. Example:

#AutoIt3Wrapper_AU3Check_Parameters=-q -d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 -w 7

Global $a = "test"

test()

Func test()
    If (IsDeclared("a")) Then
        ConsoleWrite($a)
    Else
        ConsoleWrite("Not declared")
    EndIf
EndFunc


来源:https://stackoverflow.com/questions/23634227/how-do-i-access-global-variables-in-local-scope-without-possibly-used-before-de

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!