Page 1 of 1

[solved] if A or B

Posted: 01 Oct 2007 01:01
by alasdair
is there any way of getting an if A or B (do something) construct?

Posted: 05 Oct 2007 14:19
by jeb
Hi,

yes there is a possible way.
if you want to know if x=3 or y=4 try this.

@echo off
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

set x=%1
set y=%2
call :logic_or "%x%==3" "%y%==4" result

if %result%==1 ( echo a or b is true ) else ( echo both wrong)
goto:eof

::::::::::::::::::::::
:logic_or
set %~3=0
if %~1 set %~3=1
if %~2 set %~3=1
goto :eof

Wow

Posted: 05 Oct 2007 15:29
by alasdair
this dos command shell is wierd. But thanks for the tip, I think I will use it because I have had to duplicate a lot of code. This looks almost like a gosub (like we used to use so many years ago ..)

Posted: 30 Jan 2008 23:41
by DosItHelp
Yes batch is wired sometimes and makes one thinking. Nice function jep!
How about this inline alternative:

Code: Select all

set "true="
if "%~1"=="a" set "true=Y"
if "%~1"=="b" set "true=Y"
if "%~1"=="c" set "true=Y"
if defined true (echo.At least one condition was TRUE) else (echo.All FALSE)


The good think about it:
The number of OR conditions is not limited, just add more if [COND] set "true=Y".
It workes within blocks, i.e.:

Code: Select all

for /L %%N in (1,1,6) do (
    set "true="
    if "%%N"=="1" set "true=Y"
    if "%%N"=="2" set "true=Y"
    if "%%N"=="3" set "true=Y"
    if "%%N"=="5" set "true=Y"
    if defined true (echo %%N is prime) else (echo %%N is not prime)
)
Output:
1 is prime
2 is prime
3 is prime
4 is not prime
5 is prime
6 is not prime

Enjoy :wink:

Posted: 31 Jan 2008 03:08
by jeb
Ok, I prefer functions instead of too much inline code.

So here my simple solution.

The good think about it:
The number of OR conditions is not limited, just add a compare statement. :)

Code: Select all

@echo off
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

for /L %%N in (1,1,6) do (
    call :logic_or result "%%N==1" "%%N==2" "%%N==3" "%%N==5"
    if $!result!==$1 (echo %%N is prime) else (echo %%N is not prime)
)
goto :eof

:::::::::::::::::::::::::
:logic_or <resultVar> expression1 [[expr2] ... expr-n]
SETLOCAL
set logic_or.result=0
set "logic_or.resultVar=%~1"

:logic_or_loop
if "%~2"=="" goto :logic_or_end
if %~2 set logic_or.result=1
SHIFT
goto :logic_or_loop

:logic_or_end
(
  ENDLOCAL
  set %logic_or.resultVar%=%logic_or.result%
  goto :eof
)


good look
Jan Erik