Search code examples
nsis

Avoid duplicated function code in NSIS


Currently, I have the following scripts code.

Section "Uninstall"
...
...
Call un.DeleteDirIfEmpty 
SectionEnd


Function GetJRE
    ; Call must not be used with functions starting with "un." in the non-uninstall sections.
    Call
FunctionEnd


Function un.DeleteDirIfEmpty
...
...
FunctionEnd

Function DeleteDirIfEmpty
...
...
FunctionEnd

Note that, I need to provide 2 versions of DeleteDirIfEmpty, so that the same operation can be performed in non-uninstall section and uninstall section.

Their code is the same, just that the naming is different. un.DeleteDirIfEmpty and DeleteDirIfEmpty

How is it possible to have only 1 function, but is callable by any section?


Solution

  • Take a look at \Include\Util.nsh, it is used to turn a macro into a function:

    !include Util.nsh
    
    !macro MyFunction
    MessageBox mb_ok "Hello World"
    !macroend
    !define MyFunction "${CallArtificialFunction} MyFunction"
    
    Section
    ${MyFunction}
    SectionEnd
    

    Note: To delete a empty directory, just use RMDir (Without /r switch)