Re: Access macro variable via an expression

Eric Blake <[email protected]>
Newsgroups gmane.comp.gnu.m4.general
Message-ID <[email protected]>
According to [email protected] 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             [email protected]
signature.asc (application/pgp-signature, 320 B)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Cygwin)
Comment: Public key at home.comcast.net/~ericblake/eblake.gpg
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAktMb6AACgkQ84KuGfSFAYC9bQCdH4sJvcdFY9JgnRQol5wCa/2I
tlwAnicK27dF1t13SXV8r3ptC9IaLPIt
=Mkl0
-----END PGP SIGNATURE-----
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.