Search code examples
variableserror-handlingcompiler-warningsautoit

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


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?


Solution

  • 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.