m4-discuss
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Access macro variable via an expression


From: Eric Blake
Subject: Re: Access macro variable via an expression
Date: Tue, 12 Jan 2010 05:48:26 -0700
User-agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.23) Gecko/20090812 Thunderbird/2.0.0.23 Mnenhy/0.7.6.666

According to address@hidden on 1/7/2010 1:44 PM:
> Folks,
> 
> Is it possible to access macro arguments using an expression?

Yes, if you use an intermediate macro.

> For example, using m4sugar's m4_for()

In fact, m4sugar's m4_for is doing something exactly like that in its
under-the-hood implementation, at least when targetting m4 1.4.x.  If you
want a study in the black magic possible with GNU m4, read the file
lib/m4sugar/foreach.m4 that ships with autoconf 2.64 or newer.

> m4_define([m4__print_arguments],
> [m4_for([aArg], 1, $#, +1, [  aArg = $aArg  ])])
> 
> m4__print_arguments(A, B, C, D, E)
> 
> And have the expression $aArg evalute to values of $1, $2 ... as
> the macro aArg ranges over 1,2, ....  That is, have the above produce
> 
> 1 = A   2 = B   3 = C

Here's one way.

dnl argn(N,args) - print the Nth argument of ARGS, provided that N > 0
m4_define([argn], [m4_pushdef([_], [m4_popdef([_])[$$1]])_(m4_shift($@))])

m4_define([m4__print_arguments],
[m4_for([aArg], 1, $#, +1, [ aArg = argn(aArg, $@)  ])])
m4__print_arguments(A, B, C, D, E)

However, it is not necessarily the most efficient, since you are passing
$@ through every iteration of m4_for.  A more efficient approach, using
modern m4sugar constructs, would be:

m4_define([_m4__print_arguments],
[m4_define([_],m4_incr(_)) _ = $1  ])
m4_define([m4__print_arguments],
[m4_pushdef([_],[0])m4_map_args([_$0], $@)m4_popdef([_])])
m4__print_arguments(A, B, C, D, E)

using _ as the incrementing counter to track how many arguments have been
visited during m4_map_args.

-- 
Don't work too hard, make some time for fun as well!

Eric Blake             address@hidden

Attachment: signature.asc
Description: OpenPGP digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]