@echo off
goto :food
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
:fruits
set i=0
for %%a in (apple banana grape lime) do (
set /A i+=1
set fruit[!i!]=%%a
)
set /a fruit=%random%%%4+1
set fruit=!fruit[%fruit%]!
exit /B
:food
for /l %%x in (1, 1, 5) do (
call :fruits
call :colorEcho 70 !fruit!
echo/
)
pause
exit
:colorEcho
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1i
由于某些我不知道的原因,此代码无法正确输出。它仅输出空格,因为出于某种原因,“fruit”变量永远不会被填充。任何人都可以向我解释这个吗?我有另一个脚本使用类似的结构工作正常,但从该脚本中提取这些部分完全打破它...任何帮助非常感谢!
答案 0 :(得分:2)
您在上一个问题的accepted answer中拥有正确的代码。 &#34;某些原因&#34;因为你的代码不起作用是你在这样的代码中引入的修改,所以你只需复制相同的方案......
有多种方法可以实现同样的目标。我总是喜欢最简单的一个;例如:
@echo off
setlocal EnableDelayedExpansion
for /F %%a in ('echo prompt $H ^| cmd') do set "BS=%%a"
:food
for /l %%x in (1, 1, 5) do (
call :fruits
call :colorEcho 70 !fruit!
echo/
)
pause
goto :EOF
:fruits
set /A i=%random%%%4+1
for /F "tokens=%i%" %%a in ("apple banana grape lime") do set fruit=%%a
exit /B
:colorEcho color text
set /P "=%BS% " > "%~2" <nul
findstr /A:%1 "^" "%~2" nul
del "%~2"
exit /B
答案 1 :(得分:1)
您必须先退格。 colorecho
函数需要定义变量。您正在跳过它,因为代码的第二行执行GOTO FOOD
。您也正在跳过SETLOCAL
命令,这会破坏水果阵列的延迟扩展。
@echo off
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
:fruits
set i=0
for %%a in (apple banana grape lime) do (
set /A i+=1
set fruit[!i!]=%%a
)
:food
for /l %%x in (1, 1, 5) do (
call :rand
call :colorEcho 70 !fruit!
echo/
)
pause
exit
:rand
set /a rand=%random%%%4+1
set fruit=!fruit[%rand%]!
GOTO :EOF
:colorEcho
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
GOTO :EOF