问题
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