Page 1 of 1
Expand 2 variables at the same time
Posted: 16 Nov 2016 16:18
by ImAhNoBoDy
I'm trying to expand 2 variables at the same time. Is this possible? The issue I'm having is during the IF statement. Instead of echoing 1 and then 2, the script echos 1 and 1.
Code: Select all
SETLOCAL ENABLEDELAYEDEXPANSION
SET i=0
SET ARR[%i%]=1
SET /A "i+=1"
SET ARR[%i%]=2
SET /A "i+=1"
SET ARR[%i%]=3
SET ARR
SET len=%i%
SET i=0
IF YO EQU YO (ECHO !ARR[%i%]!
SET /A "i+=1"
ECHO !ARR[%i%]!)
I did try variations of !ARR[!i!]!, ^!ARR[!i!]^!, !ARR[^!I^!]!, and ^!ARR[^!I^!]^! with undesirable results. Anyone can help? Thanks.
Re: Expand 2 variables at the same time
Posted: 16 Nov 2016 18:51
by penpen
If a compound statement (or block) is processed, then (normal/percentage) expansion is done before the internal commands are execute.
Example (assumed value of variable "i" os zero):
Code: Select all
(
ECHO !ARR[%i%]!
SET /A "i+=1"
ECHO !ARR[%i%]!
)
Then the expansion is computed for this this block with this result:
Code: Select all
(
ECHO !ARR[0]!
SET /A "i+=1"
ECHO !ARR[0]!
)
After that the statements are (delayed expanded and) executed one after another.
Avoid using "%i%" is a typical workaround in such a case:
Code: Select all
(
ECHO !ARR[%i%]!
SET /A "i+=1"
for %%a in (!i!) do ECHO !ARR[%%~a]!
)
penpen
Re: Expand 2 variables at the same time
Posted: 17 Nov 2016 12:04
by pieh-ejdsch
In an Array you can use this
Code: Select all
@echo off
setlocal
:::!ARR[1]!,!ARR[2]!,!ARR[3]!,!ARR[4]!::ARR[!N!]::
for /f "tokens=1,2 delims=:" %%i in ('findstr /r "^:::" "%~f0"') do (
for /l %%a in (6 3 17) do (
set /a N+=1
rem echo %%j
setlocal enabledelayedexpansion
rem echo %%j
for /f "delims=" %%b in ("%%j=%%a") do endlocal&set "%%~b"
)
rem echo %%i
setlocal enabledelayedexpansion
echo %%i
endlocal
)
Phil
Re: Expand 2 variables at the same time
Posted: 19 Nov 2016 09:10
by Yury
Code: Select all
setlocal
SET i=0
SET ARR[%i%]=1
SET /A "i+=1"
SET ARR[%i%]=2
SET /A "i+=1"
SET ARR[%i%]=3
SET ARR
SET len=%i%
SET i=0
IF YO EQU YO (
cmd/v/c ECHO !ARR[%i%]!
SET /A "i+=1"
cmd/v/c cmd/v/c ECHO !ARR[!i!]!
)
endlocal
Re: Expand 2 variables at the same time
Posted: 06 Dec 2016 05:03
by ImAhNoBoDy
The solution was to replace ECHO !ARR[%i%]! with CALL ECHO %%ARR[!i!]%%
Re: Expand 2 variables at the same time
Posted: 06 Dec 2016 09:18
by Aacini
or with FOR %%i IN (!i!) DO ECHO !ARR[%%i]!, that run faster...