Search code examples
batch-filedossubroutinedosbox

How to create a variable in a subroutine in DOSBox?


I'm creating a batch multilanguage installer in DOSBox.

I would like to create a variable in a subroutine which changes the displayed language based on the choice of the user. This is an example of the menu:

:installer
@echo off
echo SELECT LANGUAGE
echo [1] French
echo [2] Swedish
choice /c12
if errorlevel 2 goto instswedish
if errorlevel 1 goto instfrench

:instfrench
SET RETURN=okfrench
goto message
:okfrench
copy d:\french.com c:\
exit

:instswedish
SET RETURN=okswedish
goto message
:okswedish
copy d:\swedish.com c:\
exit

:message
echo I will install the software in %LANGUAGE%
choice /c:yn
if errorlevel 2 goto installer
goto %RETURN%

Probably I need to set the variable in the :installer section, so that %LANGUAGE% will display the selected language, but I'm not sure if that's right and I don't know how to do it. Could you please help me?


Solution

  • The solution is quite simple because of just two lines must be added to batch file code.

    :installer
    @echo off
    echo SELECT LANGUAGE
    echo [1] French
    echo [2] Swedish
    choice /c12
    if errorlevel 2 goto instswedish
    if errorlevel 1 goto instfrench
    
    :instfrench
    SET LANGUAGE=French
    SET RETURN=okfrench
    goto message
    :okfrench
    copy d:\french.com c:\
    exit
    
    :instswedish
    SET LANGUAGE=Swedish
    SET RETURN=okswedish
    goto message
    :okswedish
    copy d:\swedish.com c:\
    exit
    
    :message
    echo I will install the software in %LANGUAGE%
    choice /c:yn
    if errorlevel 2 goto installer
    goto %RETURN%
    

    The two inserted lines are:

    1. SET LANGUAGE=French below the line :instfrench
    2. SET LANGUAGE=Swedish below the line :instswedish

    That's it.

    But the code can be optimized further as shown below:

    @echo off
    :installer
    echo Select language:
    echo    [1] French
    echo    [2] Swedish
    choice /c:12
    if errorlevel 1 set LANGUAGE=French
    if errorlevel 2 set LANGUAGE=Swedish
    
    echo I will install the software in %LANGUAGE%
    choice /c:yn
    if errorlevel 2 goto installer
    
    copy d:\%LANGUAGE%.com c:\
    exit
    

    The order of evaluation of errorlevel on first choice is important here. The lowest number must be evaluated first and the highest number must be last because of if errorlevel number means IF errorlevel GREATER or EQUAL number. The environment variable LANGUAGE is defined twice on pressing 2 for language Swedish, first with French and next redefined with Swedish. But LANGUAGE is defined just by first IF condition with French on pressing 1.

    The selected language is used for next user prompt and if the user presses key y or Y also for copying the file.