How to create nested variables in batch?

2019-09-19 01:33发布

问题:

I am trying to get nested variables in my batch game i am creating. I want it so that it will choose a random variable and change it to X, but if it is already chosen, it should go back and choose a different number.

set 1=a
set 2=b
set 3=c
set 4=d
set 5=e

those were the variables, here is the code

setlocal enabledelayedexpansion

:eliminator
set /a eliminate=(%random * 5) / 32767 + 1
if %%eliminate%%==X goto eliminator
echo The letter !!eliminate!! was chosen
timeout 5
set %%eliminate%%=X
goto eliminator 

Now, the thing is, when I try to echo it, it writes the name of the variable instead of the value. Also, variables that have already been chosen are being chosen again. Any way I could fix this? Thanks.

回答1:

try this:

@echo off&setlocal
set "var1=a"
set "var2=b"
set "var3=c"
set "var4=d"
set "var5=e"
:loop
set /a rd=%random%%%5+1
if defined var%rd% call echo %%var%rd%%%
set "var%rd%="
set "var" >nul 2>&1 && goto:loop

..output (may vary):

d
a
c
b
e


回答2:

Your posted code is missing the closing % around random - it should read %random%.

Your formula for a random number between 1 and 5 is more complicated than need be. I would use:

set /a eliminate=%random% %% 5 + 1

To expand a "nested variable" you need !%eliminate%!

But I would completely rewrite your algorithm. I think the following does what you want:

@echo off
setlocal enableDelayedExpansion
set "chars=abcde"
set charCnt=5
:loop
set /a "pos=%random% %% charCnt, pos2=pos+1, charCnt-=1"
set "letter=!chars:~%pos%,1!"
echo The letter %letter% was chosen
set "chars=!chars:~0,%pos%!!chars:~%pos2%!"
if defined chars goto loop

The script is optimized to always pick a valid unused letter on each iteration.