www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Variable interpolation in strings

reply Justin Whear <justin economicmodeling.com> writes:
Jonathan M. Davis' recent post about string mixins reminded me of 
something I put together a couple of months ago: variable interpolation 
in strings http://dpaste.dzfl.pl/5689d535

Some of the projects I work on have lots of embedded queries which are 
assembled on the fly (not just values but column and table names). Using 
concatenation tends to break the queries up excessively, while using 
format with lots of arguments makes them hard to modify. So I took a page 
from PHP's book and implemented "$foo" style expansion.

My original thought was to allow cool syntax like x!"embedded variable: 
$foo" but template instantiations don't have access to variables from 
instantiation scope (unless you pass them explicitly via alias, of 
course).  Thus the need for string mixins.
The `inContext` version does take a struct or object which constitutes 
the set of available variables.

My ugly parsing code could be replaced (maybe, haven't actually tested 
it) by the nice version(none)'d function which uses regexs if match() was 
available for CTFE.

Justin
Jul 26 2012
next sibling parent "Adam D. Ruppe" <destructionator gmail.com> writes:
It might be useful to do this kind of thing with a filter
function:

string escape(string s) { return s.replace("\n", "\\n"); }

auto foo = "cool\nstuff";
string lol = mixin(x("blah $foo", escape));

assert(lol == "blah cool\\nstuff");
Jul 26 2012
prev sibling parent reply "Tobias Pankrath" <tobias pankrath.net> writes:
 My original thought was to allow cool syntax like x!"embedded 
 variable:
 $foo" but template instantiations don't have access to 
 variables from
 instantiation scope (unless you pass them explicitly via alias, 
 of
 course).
template mixins?
Jul 26 2012
parent Justin Whear <justin economicmodeling.com> writes:
On Thu, 26 Jul 2012 22:40:25 +0200, Tobias Pankrath wrote:

 My original thought was to allow cool syntax like x!"embedded variable:
 $foo" but template instantiations don't have access to variables from
 instantiation scope (unless you pass them explicitly via alias,
 of course).
template mixins?
No, template mixins can only add declarations: "A Tem­plateMixin takes an ar­bi­trary set of de­c­la­ra­tions from the body of a Tem­plat­eDe­c­la­ra­tion and in­serts them into the cur­rent con­text." (http://dlang.org/template- mixin.html)
Jul 26 2012