Writing Batch code in an easier way with the aid of macros

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Message
Author
siberia-man
Posts: 110
Joined: 26 Dec 2013 09:28
Contact:

Re: Writing Batch code in an easier way with the aid of macros

#16 Post by siberia-man » 13 Nov 2018 07:35

A-ha! I see the root of this trick.

This one:

Code: Select all

%echo /a% r={1+1}
works as follows:

Code: Select all

for %%n in (1 2) do if %%n==2 (%\n%
...
) else setlocal EnableDelayedExpansion ^& set argv= r={1+1}
So the loop of two iterations is the main part of macros. Cool!

Aacini
Expert
Posts: 1564
Joined: 06 Dec 2011 22:15
Location: México City, México

Re: Writing Batch code in an easier way with the aid of macros

#17 Post by Aacini » 13 Nov 2018 08:32

Yes. I explained this point in detail at this reply:
Aacini wrote:
12 Dec 2011 05:19

. . .

Suppose you have a macro-function that is usually executed this way:

Code: Select all

for /F "tokens=1-26" %%a in ("param1 param2 resultvar") do %macroFunc%
How we may execute the macro in the following way?

Code: Select all

%macroFuncWithParams% param1 param2 resultvar
Parameters placed after the macro needs to be taken and moved inside the FOR parentheses; this may be achieved by a two-step process:

1- Get the parameters
2- Execute the macro with them

That is, the macro must be executed two times: in the first step the parameters will be stored in an (argv) variable, and in the second step the macro will be really executed:

Code: Select all

for %%s in (get_params exec_macro) do (
   if %%s == get_params (
      set argv=<rest of the line placed after the macro>
   ) else ( rem %%s == exec_macro
      for /F "tokens=1-26" %%a in (!argv!) do %macroFunc%
   )
)
However, the <rest of the line> is physically placed after the macro. This means that set argv= command must be the last part of the macro definition:

Code: Select all

for %%s in (1 2) do (
   if %%s == 2 (
      for /f "tokens=1-26" %%a in (!argv!) do %macroFunc%
   ) else (
      set argv=<rest of the line...>
   )
)
There are still two parentheses after set argv=, but we can simply eliminate they because the FOR and ELSE part parentheses are placed here just for legibility:

Code: Select all

for %%n in (1 2) do if %%n == 2 (
      for /f "tokens=1-26" %%a in (!argv!) do %macroFunc%
   ) else set argv=
This way, although the parts seems to be upside down, they execute in the right order...
Antonio

Post Reply