What are macros?
Asked by
alley (
7)
December 9th, 2006
Observing members:
0
Composing members:
0
15 Answers
A shortcut that will make several things function/occur in a sequence
Yep. Well stated, amccabe.
what are you looking to use macros with?
If you are using macros in Word or Excel, trying using the "record new macro" function. Then make your text centered, bold, or other steps, hit stop, and view the macro you just recorded. It will give you a quick look at how they work.
A "Macro" is a single command that causes the execution of a series of commands. Macros can remove some of the drudgery of having to repeat the same sequences of commands over and over again. In programming they are a useful construct which allow a programmer to create "super instructions" that look like a simple instruction, such as MOVE A,B , but actually contain many other instructions. In some languages macros may be nested, where a new macro is defined that includes other macros within in.
Some programming languages such as Lisp allow you to define operators called 'macros' which provide rules for transforming an expression using that operator into another expression by following the rules provided. The transformation is done by (typically) the compiler or the interpreter. At its simplest, this allows you to perform standard tasks in a shorthand fashion. More powerfully, you can even define your own private programming language which is transformed into the existing already implemented programming language.
Here is an example in Lisp. When you do input/output to a file, you must open the file, do what you want, and then close the file. If you forget the close the file, eventually the program will fail because you will run out of file descriptors. Lisp has the macro with-open-file which automatically does the opening and closing tasks. Here is Lisp code which does that (I do not expect most people to be able to follow it, but I wanted to show what macro defining code looks like(:
(defmacro with-open-file ((var &rest; open-args) &body; body)
`(let ((,var (open ,@open-args)))
(unwind-protect (progn ,@forms)
(close ,var))))
and a call looks like
(with-open-file (s "myfile" :direction :output)
(print "Hello!" s))
and you end up when you run that form with a file named myfile containing Hello!.
Answer this question
This question is in the General Section. Responses must be helpful and on-topic.