Page 1 of 1
how to make an array by function and by local variable of the function
Posted: 05 Apr 2019 05:57
by sincos2007
Code: Select all
@echo off
set /a n=99
set ret=
call :test3 ret
echo show array:
echo %ret.Array[0]%
echo %ret.Array[1]%
echo %ret.Array[2]%
echo %ret.Array[3]%
ECHO Press any key to close the windows...
pause>NUL
goto :eof
:test3
setlocal
set /a n=0
:Loop-Start
if %n% GEQ 3 goto :Loop-End
set %~1.Array[%n%]=V%n%
set /a n=n+1
goto :Loop-Start
:Loop-End
endlocal
goto :eof
Hi,
I have written a function named test3 who make an array by its local variable named n(notice that there is a global variable named n). The function test3 returns the array to first parameter of it. But the result is incorrect
Thanks
Re: how to make an array by function and by local variable of the function
Posted: 05 Apr 2019 06:14
by aGerman
notice that there is a global variable named n
That gets overwritten with 0 in the scope of your function. And every variable you define inside of the function will be discarded because of the endlocal command at the end.
But the result is incorrect
What would be the result you expect?
Steffen
Re: how to make an array by function and by local variable of the function
Posted: 05 Apr 2019 06:49
by jeb
You need to preserve the values in the ENDLOCAL-Block.
Code: Select all
@echo off
set /a n=99
set ret=
call :test3 ret
echo show array:
echo %ret.Array[0]%
echo %ret.Array[1]%
echo %ret.Array[2]%
echo %ret.Array[3]%
goto :eof
:test3
setlocal EnableDelayedExpansion
set /a n=0
for /L %%n in (0 1 3) DO (
set "%~1.Array[%%n]=V%%n"
)
REM *** Leaving the scopt, preverve the values
set "_return="
for /L %%n in (0 1 3) DO (
if defined _return (
set "_return=!_return!&"
)
set "_return=!_return!set "%~1.Array[%%n]=!%~1.Array[%%n]!""
)
(
endlocal
%_return%
)
goto :eof
Re: how to make an array by function and by local variable of the function
Posted: 05 Apr 2019 07:59
by Squashman
Re: how to make an array by function and by local variable of the function
Posted: 05 Apr 2019 09:55
by Aacini
Code: Select all
@echo off
set /a n=99
call :test3 ret
echo show array:
echo %ret.Array[0]%
echo %ret.Array[1]%
echo %ret.Array[2]%
echo %ret.Array[3]%
ECHO Press any key to close the windows...
pause>NUL
goto :eof
:test3
setlocal
for /L %%i in (0,1,3) do set "%~1.Array[%%i]=V%%i"
set localEnv=1
for /F %%v in ('set %~1.Array[') do (
if defined localEnv endlocal
set "%%v"
)
goto :eof
Antonio
Re: how to make an array by function and by local variable of the function
Posted: 06 Apr 2019 02:28
by sincos2007
Hi jeb,
This really works, just by preserve values in EndLocal block. Following is workable code for subroutine test3:
Code: Select all
:test3
setlocal EnableDelayedExpansion
set /a n=0
for /l %%i in (0,1,3) do (
set s1=V!n!
if defined _ret (
set _ret=!_ret! ^&
)
set _ret=!_ret!set %~1.Array[!n!]=V!n!
set /a n=n+1
)
(
endlocal
%_ret%
)
goto :eof
Thanks.