Interpolated strings

Nick Sabalausky (Abscissa) via Digitalmars-d digitalmars-d at puremagic.com
Thu Apr 20 11:40:09 PDT 2017


On 04/20/2017 06:23 AM, Martin Tschierschke wrote:
> and this not?
>
> import scriptlike;
>
> // with exho definition outside the scope of the used vars
>
> auto exho(string x)(){return mixin("writeln("~interp!x~")");}
>
> void main()
> {
>
>    auto name = userInput!string("Please enter your name");
>    auto age = userInput!int("And your age");
>
>    writeln(mixin(interp!"${name} you are app. ${age*365} days old"));
>
>    exho!"${name} and this are app ${age*365*24} hours!";
> }

The definition for:

exho!"${name} and this are app ${age*365*24} hours!"

...once the template is instantiated and the mixin is evaluated, is 
turned into this:

auto exho()
{
	return writeln("${name} and this are app ${age*365*24} hours!");
}

But, there is no identifier "name" or "age" within the scope of exho.

However, if exho is instead defined as a nested function WITHIN main, 
then as with any (non-static) nested function, it DOES have access to 
the local variables from the outer function.

This, incidentally, is exactly why interp!"..." needs to be a string 
mixin in the first place.



More information about the Digitalmars-d mailing list