0

So, I'm making a calculator that allows its users to name their previous result in order to use them in future calculations. How it works is that when you give a name to a previous result, it creates a variable with the name chosen and its value is then set to whatever the previous result is. It looks something like this:

set /p equation=
::variables need to be replaced here
set /a result=%equation%
::giving a name
set /p name=
set %name%=%result%

The problem is, I cannot figure out a way to get the value of the variable in the equation since the equation is also a variable, so whenever I add the equation in a command with %equation%, it just replaces it with something like 1+%named_result%. Is there a way I could turn the equation with the same one but where the variables are replaced with their values? (set equation=%equation% does not work)

Itchydon
  • 2,572
  • 6
  • 19
  • 33
TheBoxyBear
  • 371
  • 2
  • 15
  • Read on [delayedexpansion](http://ss64.com/nt/delayedexpansion.html) and using call/for to [force another expansion](https://stackoverflow.com/questions/1199931/how-to-expand-a-cmd-shell-variable-twice-recursively) –  Aug 24 '17 at 22:27
  • 1
    That is not necessary. Any _variable name_ that appears in the equation of `SET /A` command is automatically replaced by the variable value. I.e. `set equation=1+named_result` – Aacini Aug 26 '17 at 01:04

1 Answers1

1
for /f "tokens=1*delims==" %%a in ('set %name% 2^>nul') do if /i "%%a"=="%name%" set "result=%%b"

set %name% lists all of the variables that start %name% in the format name=value. The 2>nul suppresses error messages if name is not defined. the caret (^) escapes the > telling cmd that the > is part of the set command, not the for.

The for /f splits the set line into two parts - that before the delimiter and that after, so name goes to %%a and value to %%b. Now set will output any name that starts with name so it will match name, named names etc. consequently, we need to choose the output line where the name exactly matches (hence the if) and to make the match case-insensitive (the /i on the if command.

And if the test is passed, assign the value to your chosen variable.

Magoo
  • 77,302
  • 8
  • 62
  • 84
  • I put Batch away in favor of C# now. But thanks anyway. I'm sure it will be useful to someone at some point. :) – TheBoxyBear Mar 20 '18 at 00:45