December 11, 2013 Re: global vs context variable | ||||
---|---|---|---|---|
| ||||
Posted in reply to luka8088 | On 12/11/13 09:21, luka8088 wrote: > Hi everyone! > > I would like to address the issue of global variables (or states). In > general my opinion is that they are bad solely because they (in most > cases) lack the ability of alternative values (or states) or ability to > alter them in user friendly way. > > For example, take write function from std.stdio. For a third party [...] > void writeOutput () { > writeln("example output"); > } > > void main () { > writeOutput(); > > standardOutputContext(file("example.txt"), { > writeOutput(); > }); > } import std.stdio; void writeOutput () { writeln("example output"); } void main () { writeOutput(); { auto ex = Push!stdout(File("example.txt", "w")); writeOutput(); } writeOutput(); } struct Push(alias A, T=typeof(A)) { T old; this(T a) { old = A; A = a; } ~this() { A = old; } } Last time I checked, 'with' was still broken (the object is destroyed too soon), but once that is fixed you should be able to do: with (Push!stdout(File("example.txt", "w"))) writeOutput(); artur |
Copyright © 1999-2021 by the D Language Foundation