I edited my prior post to fix a bug in the macroLib.bat code. I had forgotten the ENDLOCAL at the end of macro.1, macro.2 and macro.3. The test program was giving the correct visual output, but the local macro variables were still active after the "calls". All is good now (till the next bug).
=====================================
Ed Dyreen wrote:So you are reducing the overhead aswell! By derefferencing first, it won't have to be done at execution phase brilliant
Thanks, but I'm not so sure it is brilliant, more like the only way that it can work. Even your examples were expanded during the definition phase when you used traditional delayed expansion. The big advantage of
${macroName} / derefMacro is we take control of when and how the macro is expanded, thus avoiding all of the problems associated with delayed expansion using
!macroName!. Given that we can't predict how many layers deep the calls will go, trying to figure out how many times to escape the ^, ! and <LF> characters would be a nightmare!
=====================================
Given that the macros enable delayed expansion within their body, we can't call them directly from the command prompt. They must be called from a batch file. But wouldn't it be nice to run them from the command prompt? I thought so, so I wrote:
callMacro.bat:
Code: Select all
@echo off
setlocal enableDelayedExpansion
set "macro.temp=!%~1!"
endlocal & for /f "tokens=2-27" %%a in ("%*") %macro.temp%
exit /b
This very small batch file is simply a batch wrapper around a macro. To call macro.StrLen you would use:
Code: Select all
callMacro macro.StrLen strVar [rtnVar]
or
call callMacro macro.StrLen strVar [rtnVar]
where [rtnVar] is the optional output variable.
We have reintroduced the call function overhead, but we are not likely to notice the impact during an interactive session!
Of course I am assuming the batch library (macroLib.bat in my test cases) has already been loaded (run) prior to calling callMacro.bat, and that callMacro.bat is in the current directory or the PATH.
CallMacro.bat can also be useful within a batch file when the definition of a macro or other compound statement is exceeding the limits of DOS. Using the macro directly expands the macro within the compound statement. Calling :callMacro takes the expansion out of the compound statement and puts it in the function. The only requirement is that callMacro.bat reside in the current directory or the PATH. Or you could copy the function into your batch file.
CallMacro.bat is not bullet proof - it does not gracefully handle arguments with special characters, especially the caret "^". Special handling could be added, but that will add extra overhead.
Dave Benham