Windows 批处理变量
我在从另外两个变量的变量中获取值时遇到问题。可能听起来很复杂,因为我的英语不是最好的。
我使用变量 rXY 来制作 xy 网格,其中 X 是 x 位置,Y 是 y 位置。我用随机字符填充网格,但现在我想获得一个点的值。
echo %r23% 会起作用,但是如果我向用户询问坐标(set /P p_x=)那么 echo %r%p_x%%p_y%% 将不起作用。
是否有可能通过这种方式获得价值?
代码示例:
echo off
cls
FOR /L %%Y IN (1,1,4) DO (FOR /L %%X IN (1,1,4) DO set r%%X%%Y=.)
echo Y
echo 4 %r14% %r24% %r34% %r44%
echo 3 %r13% %r23% %r33% %r43%
echo 2 %r12% %r22% %r32% %r42%
echo 1 %r11% %r21% %r31% %r41%
echo 0 1 2 3 4 X
set /P input=Please enter X and Y pos:
set p_x=%input:~0,1%
set p_y=%input:~1,2%
echo X=%p_x%
echo Y=%p_y%
echo [2,3]=%r23%
echo %r%p_x%%p_y%
pause
I have problem with getting value from variable trought two other variable. May sound complicated cause my english is not best.
I use variable rXY, to make xy grid, where X is x pos and Y is y pos. I filled grid with random chars but now I want to get value of one point.
echo %r23% will work, but if I ask coordinates from user (set /P p_x=) then
echo %r%p_x%%p_y%% will not work.
Is it even possible to get value this way?
Example of code:
echo off
cls
FOR /L %%Y IN (1,1,4) DO (FOR /L %%X IN (1,1,4) DO set r%%X%%Y=.)
echo Y
echo 4 %r14% %r24% %r34% %r44%
echo 3 %r13% %r23% %r33% %r43%
echo 2 %r12% %r22% %r32% %r42%
echo 1 %r11% %r21% %r31% %r41%
echo 0 1 2 3 4 X
set /P input=Please enter X and Y pos:
set p_x=%input:~0,1%
set p_y=%input:~1,2%
echo X=%p_x%
echo Y=%p_y%
echo [2,3]=%r23%
echo %r%p_x%%p_y%
pause
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用(可怕的)延迟扩展。
%variables%
在解析该行时展开,!variables!
– 在实际执行时。Use the (horrible) delayed expansion.
%variables%
are expanded when the line is parsed,!variables!
– at the time of actual execution.您可以以不同的方式实现延迟扩展:
几乎不那么可怕,但至少使您无需发出特殊命令(老实说,仍然是值得怀疑的优势)。
它是如何运作的。双精度
%
计算为文字%
,然后将两个变量计算为其值,最后您还有一个双精度%
,即进行相应处理。这是在执行该行之前立即发生的第一次解析。在执行时,该行采用(例如)
CALL ECHO %r21%
的形式。正如您可以猜到的,当调用
CALL
命令时,会发生第二次解析,这次%r21%
被正确地评估为其各自的值。You can achieve the delayed expansion differently:
Hardly less horrible, but at least spares you the need to issue the special command (still, questionable advantage, to be honest).
How it works. The double
%
evaluates to the literal%
, then the two variables are evaluated to their values, and lastly you have one more double%
which is processed accordingly.This is the first parsing that occurs immediately before executing the line. By the time of execution the line takes the form of (for example)
CALL ECHO %r21%
.As you can guess, when the
CALL
command is invoked, the second parsing takes place, and this time%r21%
is rigtfully evaluated to its respective value.