我正在制作一个简单的批处理游戏,我正在尝试找出如何使用名称未知的变量的值。例如:
我不知道var1
变量的名称或值,因为它是在游戏的早期点自动生成的。
我唯一知道的是第3行:set var3=var2
我需要我的游戏在if语句中使用“var1”的值,如最后一行所示
我该怎么做?
set var1=5
set var2=var1
set var3=var2
if ??? EQU something something...
答案 0 :(得分:2)
它进行了一些编辑,但我终于想出了一个真正的防弹选项(方法5)。
在方法5中,如果var3被包含"
的变量名替换,那么您将不得不转义一些引号。但是如果你足够复杂,可以在变量名中加上引号,那么你就已经知道如何做了: - )
@echo off
setlocal
set var1=5
set var2=var1
set var3=var2
::method 1 - Without using delayed expansion. (this is relatively slow and unsafe)
:: the initial expansion uses 1 % and no CALL
:: the 2nd expansion uses CALL and 2 %%
:: the 3rd expansion uses CALL and 4 %%%%
:: each additional expansion would require another CALL and doubled percents
call call set "test=%%%%%%%var3%%%%%%%
if "%test%"=="5" echo Method 1 works: Value of "unknown var"=%test%
::The remaining methods use delayed expansion. They are safer and faster.
setlocal enableDelayedExpansion
::method 2 - Using normal and delayed expansion and a temp variable.
:: Almost always works, but can fail in rare cases where variable
:: name contains "
set "test=!%var3%!"
if "!%test%!"=="5" echo Method 2 works: Value of "unknown var"=!%test%!
::method 3 - Using normal and delayed expansion without using any temp variable.
:: This works for sensible variable names, but fails if name contains
:: * or ?. Also can fail if variable name contains "
for %%A in ("!%var3%!") do if "!%%~A!"=="5" echo Method 3 works: Value of "unknown var"=!%%~A!
::method 4 - Using normal and delayed expansion without using any temp variable.
:: This almost always works, but can fail in rare cases where variable
:: name contains "
for /f "eol==delims=" %%A in ("!%var3%!") do if "!%%A!"=="5" echo Method 4 works: Value of "unknown var"=!%%A!
::method 5 - Using delayed expansion without using any temp variable.
:: This always works!
for /f "eol==delims=" %%A in ("!var3!") do for /f "eol==delims=" %%B in ("!%%A!") do if "!%%B!"=="5" echo Method 5 works: Value of "unknown var"=!%%B!