Well, that macro stuff seems closest as far as the execution goes in other languages, but traditionally in batch, it's calling either a separate batch file, or a label (my preference). But it seems you mean, dynamically creating a function? Not sure I understand the purpose, but it looks like you're on the right track. Though, utilizing the shift command many more arguments could be used, but I think writing it in one argument would be better due to all the bad spaces.
Did you know that batch files are self-modifiable? Though I think if you add code -before- the current position, it will screw up. So if for some reason you want a batch file to dynamically create a function onto itself rather than a new file, I think...
Code: Select all
@echo off
call :addNewFunction %0 greet "echo:Hello World.&echo:echo:What's up?"
call :greet
pause
exit
:addNewFunction
(
echo:
echo::%2
echo:%~3
echo:exit/b
)>>%1
exit/b
Notice that:
1. We have to pass the path of the current file to the label call, because the arguments change during a call and we need that to append to the current file.
2. Note that only the first echo is provided for the actual commands, as the bare necessity.
3. Beware that every time you run the file, it'll recreate those functions lol. A fix could be put in place.
4. Reproducing special characters like % and & require escaping them, as they will be interpreted by Command Prompt during the function's creation.
EDIT: Fixed #3. Adds a simple label and "defined" argument clause.
Code: Select all
@echo off
call :addNewFunction %0 greet "echo:Hello World.&echo:echo:What's up?"
call :greet
pause
exit
:addNewFunction
call :%2 func_defined 2>nul&&exit/b
(
echo:
echo::%2
echo:if "%%~1"=="func_defined" exit/b
echo:%~3
echo:exit/b
)>>%1
exit/b