Sunday, November 12, 2023

Batch Script : The mystery of setting variable inside for loop

 Spend whole day to figure out how to get a random terms inside for loop.


Tried %%list[!index!]%% , %list[!index!]% , !list[%index%]! many many combination. 

Finally, a "call" made the magic.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@echo off

setlocal enabledelayedexpansion



REM Define the list

set "list[0]=a"

set "list[1]=b"

set "list[2]=c"



REM Enable delayed expansion within the loop

for /l %%i in (1,1,3) do (

    REM Generate a random index within the range of the list

    set /a "index=!random! %% 3"

    

    REM without that call, cannot get the string

    call set "randomString=%%list[!index!]%%"

    

    REM Print the iteration number and the corresponding random string

    echo Random string for iteration %%i: !randomString!

)



endlocal

No comments:

Post a Comment

Something about Renpy For loop error : expected statement.

 It takes me over hour to debug. The simple fact is that under label, we cannot use For loop. One while is valid to be used under label. To ...