Search code examples
nsis

NSIS: How to check if a var exists


What is the best way to check if a var exists in NSIS?

Currently I do something like this:

${If} $NonExistentVar == $$NonExistentVar

But this won't work as expected in case an existing var some_var have the value of $some_var, I know it's rare but, is there a better way of checking it?

section non_existent_var
    detailprint "non existent: $NonExistentVar"
    var /global ExistentVar
    detailprint "existent: $ExistentVar"
    ${If} $NonExistentVar == $$NonExistentVar
        detailprint "PASS: NonExistent doesn't exist"
    ${Else}
        detailprint "FAIL: NonExistent exists"
    ${EndIf}

    ${If} $ExistentVar == $$ExistentVar
        detailprint "FAIL: ExistentVar doesn't exist"
    ${Else}
        detailprint "PASS: ExistentVar exists"
    ${EndIf}

    strcpy $ExistentVar "$$ExistentVar"

    ${If} $ExistentVar == $$ExistentVar
        detailprint "FAIL: ExistentVar doesn't exist"
    ${Else}
        detailprint "PASS: ExistentVar exists"
    ${EndIf}
SectionEnd

gives:

non existent: $NonExistentVar
existent: 
PASS: NonExistent doesn't exist
PASS: ExistentVar exists
FAIL: ExistentVar doesn't exist
Completed

Solution

  • Why not use a define? This is a check that should happen at compile time after all.

    !macro DeclareDetactableVariable name
    !ifndef VAR_${name}
    Var /Global ${name}
    !define VAR_${name}
    !endif
    !macroend
    
    !insertmacro DeclareDetactableVariable foo
    !ifdef VAR_foo
    ...
    !endif