1

我正在制作一个简单的批处理游戏,并试图找出如何使用名称未知的变量的值。示例:
我不知道var1变量的名称或值,因为它是在游戏早期自动生成的。
我唯一知道的是第 3 行:set var3=var2.
我需要我的游戏在 if 语句中使用“var1”的值,如最后一行所示。
我该怎么做?

set var1=5
set var2=var1
set var3=var2
if ??? EQU something something...
4

1 回答 1

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!
于 2012-07-26T23:29:55.480 回答