Passing literal arguments

Just like functions, macros can also take arguments. In fact, taking an argument is the most common occurrence for a macro. The simplest type of argument is literals, such as numbers, symbols, and strings.

In order to utilize these arguments in the returned expression, we can use the interpolation technique that we learned in the last section. Consider the following code:

macro hello(n)
return :(
for i in 1:$n
println("hello world")
end
)
end

The hello macro takes a single argument, n, which is interpolated into the expression when the macro is run. As before, we can just invoke the macro as follows:

As we learned earlier, parentheses are not required, so we can also call the macro as follows:

You can try a similar exercise with string or symbol arguments. Passing literals is easy to understand because it works in the same way as functions. But there is indeed a subtle difference between macros and functions, which we will discuss in detail in the following section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.123.120