Thanks a lot Dave, it works now!
Code: Select all
set while=for %%n in (1 2) do if %%n==2 (%\n%
call :StrLen argv argvLen=%\n%
set "body=!argv:*do=!"%\n%
call :StrLen body bodyLen=%\n%
set /A condLen=argvLen-bodyLen-2%\n%
for %%a in (!condLen!) do set "cond=!argv:~0,%%a!"%\n%
echo for /L %%%%w in (1,0,1^^) do if !cond! !body! else exit ^^^^!whileResult^^^^!^> whileBody.bat%\n%
cmd /V:ON /Q /C whileBody%\n%
endlocal ^& set whileResult=^!errorlevel^!%\n%
) else setlocal EnableDelayedExpansion ^& set argv=
EDIT: I added /V:ON switch to avoid an error described below.
WHILE macro is used this way:
The condition is exactly the same of IF command.
To include multiple commands, terminate each line with %\n% (macro style).
EDIT: Parentheses are mandatory.
To get a variable value in the condition or while body, enclose its name between %!%; this method is easier to remember than multiple ^^^^... and looks balanced (and I like it!)
"whileResult" variable preserve its (numeric) value after the while ends.
Some examples:
Code: Select all
:factorial N R=
setlocal
set num=1
set whileResult=1
%while% %!%num%!% leq %1 do ( set /A whileResult*=num, num+=1 )
endlocal & if "%2" neq "" (set %2=%whileResult%) else echo %whileResult%
exit /B
:lcm n1 n2 lcm=
setlocal
set /a "whileResult=%1, j=%2"
%while% %!%j%!% neq 0 do ( set /a k=j, j=whileResult%%%%j, whileResult=k )
set /a j=%1*%2/whileResult
endlocal & if "%3" neq "" (set %3=%j%) else echo %j%
exit /B
call :factorial 10 factor=
echo Factorial of 10: %factor%
echo/
call :lcm 3527 3784 var=
echo Least common multiple of 3527 and 3784: %var%
echo/
echo Calculation of e:
set /A digits=6, one=1
for /L %%i in (1,1,%digits%) do set one=!one!0
set /A num=0, fact=1, factXone=fact*one, whileResult=0
echo #- #%!% term summation
%while% %!%factXone%!% gtr 0 do ( %\n%
set /A term=one/fact, whileResult+=term %\n%
echo %!%num%!%- %!%fact%!% %!%term%!% %!%whileResult%!% %\n%
set /A num+=1, fact*=num, factXone=fact*one %\n%
)
echo Number e = !whileResult:~0,-%DIGITS%!.!whileResult:~-%DIGITS%!
echo/
Results:
Code: Select all
Factorial of 10: 3628800
Least common multiple of 3527 and 3784: 13346168
Calculation of e:
#- #! term summation
0- 1 1000000 1000000
1- 1 1000000 2000000
2- 2 500000 2500000
3- 6 166666 2666666
4- 24 41666 2708332
5- 120 8333 2716665
6- 720 1388 2718053
7- 5040 198 2718251
8- 40320 24 2718275
9- 362880 2 2718277
Number e = 2.718277