1

I'm trying to simulate a while loop in Batch, here's my code:

@echo off
set test=0

:main
call:whileLSS %test% 4 :count

:whileLSS
if %1 LSS %2 (
    echo %1
    call%3
    goto whileLSS
)
goto:EOF

:count
set /a test=%test%+1
goto:EOF

This just outputs 0s, instead of outputting "0 1 2 3" like I want it to.

The problem is that the loop goes forever because %1 doesn't have the most updated value of test.

Is this the right approach?

How do I update the value of %1?

Is there a way to not have to hardcode operators like LSS?

3

3 Answers 3

3

as you've been told, you can't change an Arg, you can take the arg as a reference and change the referenced var, this requires delayed expansion here.
Your first sub also wasn't separated from flow.

This Batch:

@echo off&Setlocal EnableDelayedExpansion
set test=0

:main
call:whileLSS test 4 :count
Goto :Eof

:whileLSS
if !%1! LSS %2 (
    echo !%1!
    call%3
    goto whileLSS
)
goto:EOF

:count
set /a test+=1
goto:EOF

Produces this output:

0
1
2
3

Edit
The operator to the if may also be suppied as an arg:

@echo off&Setlocal EnableDelayedExpansion
set test=0

:main
call:while test LSS 4 :Increment
set test=10
call:while test GTR 4 :Decrement

Goto :Eof
:while
if !%1! %2 %3 (
    echo !%1!
    call %4 %1
    goto while
)
goto:EOF

:Increment
set /a %1+=1
goto:EOF

:Decrement
set /a %1-=1
goto:EOF
Sign up to request clarification or add additional context in comments.

4 Comments

Is there a way to take another argument to use an operator? That way I don't have to make a while for LEQ, GTR and GEQ
@Nihil yes, just tested it, see append to the answer.
@Nihil Did another edit to the subs, but I now feel a bit vrtualized ;-) And I personally prefer straight code I still understand a year later.
strange, for some reason when I tried having a fourth argument it always had the value of "4", now it works :)
0

Like this may be?

@echo off

:main
set /a a=1
set /P i=Enter i:
call:whileLSS %a% %i%

:whileLSS
    echo %1
    if %1 LSS %2  call:reinitialize %1 %2
    goto:EOF


:reinitialize
    set /a c=%1
    set /a b=%c%+1
    set /a d=%2
    call:whileLSS %b% %d%

goto:EOF

1 Comment

even if this seems to answer the question, it would be best to provide explanations on your code and on the OP code (why it didn't work, why your code does what's required)
0

Try this:

@echo off 
Setlocal EnableDelayedExpansion
set test=0

:main
call :whileLSS !test! 4 
Goto :Eof

:whileLSS
set i=%1
set j=%2

:loop
if !i! LSS !j! (
    echo !i!
    call :count
    goto :loop
)

goto :EOF

:count
set /a i+=1
goto :EOF

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.