Solved need help with batch variables

January 8, 2014 at 20:10:12
Specs: Windows 7
I'm trying to use an if statement like so...if c%value% == 1 goto new bookmark I have multiple variables labled c1-c100. Most of which are blank but some have a 1. The user inputs the value variable so I want it to be if c%number the user Inputs, or value == 1 goto a defined place...how do I do this...the above method has already been tryed obviously or I wouldn't be asking for help

See More: need help with batch variables

Report •

#1
January 8, 2014 at 20:47:30
This confuses a lot of people. C is taken literally, NOT as a variable value. Here is example:
set C1=98
set /p z=val:
(user enters 1)
echo C%z%
multiple choice, whaddya get:
a) C98
b) C1
c) 98
the answer is "b", because "C" is a literal, not a variable-name. To do what you intend, you have to use delayedexpansion, which allows "!" to supreceded "%" in layers of interpretration:
echo !C%z%!
gives you what you want. Here's a sample to try:
@echo off & setlocal
set x=
set /p x=element of 'c' that will recieve value:
set c%x%=test
echo 1st level: c%x%
echo 2nd level: !c%x%!
pause
for /L %%a in (1 1 10) do if defined c%%a (echo %%a:!c%%a!) else (echo %%a:undef)

note that if you need to scan for defined/undefined, THEN you drop back to normal notation:
for /L %%a in (1 1 10) do if defined c%%a (echo c%%a) else (echo undef)

hope this helps!

ps: here is vbscript version to do the same kind of thing, but more levels:
a="1"
wscript.echo a
one="two"
wscript.echo eval(a)
two="third"
wscript.echo eval(eval(a))

but batch might be unique in allowing referse-indirect:
set Iam=myself
set %Iam%=whoIam
set m

message edited by nbrane


Report •

#2
January 8, 2014 at 21:49:22
Not quite what I ment...its hard to explain...here is what I have:
Set /a value = 2
Set c1=
Set c2=
Set c3=
...etc. till set c3=100
Set /a chance=%random% %%100 +1
Set c%chance% = x
...say chance ended up being 3. It would set c3=x.
Set /p move=:
If %move% == up set /a value + 1
If c%value% == x goto bookmark
...does that make any sense?...I want to use the value variable along with c in the if statement

Report •

#3
January 8, 2014 at 22:13:52
✔ Best Answer
Set c%chance% = x

That part works (above). below does not:

If c%value% == x goto bookmark
...does that make any sense?...I want to use the value variable along with c in the if statement

Yes. Like i kind-of said, subsittute instead the following:
If !c%value%! == x goto bookmark

This method is very very common in this forum, and should present no problem. BUT
you have to have delayed-expansion enabled. to for this to work:

setlocal enabledelayedexpansion

most systems now have that as default, but always to be sure...

message edited by nbrane


Report •

Related Solutions

#4
January 9, 2014 at 04:40:56
Thank you so much Lol see I tryed that out the !c%value%! But it didn't work Cruz I didn't do setlocal enabledelayedexpansion. Thank you a lot!

Report •

Ask Question