www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Declaring a reusable formula and using it in other scopes.

reply BoQsc <vaidas.boqsc gmail.com> writes:
`bool nextArgumentDoesNotReachEndOfArray = i + 1 < args.length;`

How can I declare it out of scope and reuse it in any scope that 
has `i` and `args.length` declared?
Feb 12 2022
parent reply Basile B. <b2.temp gmx.com> writes:
On Saturday, 12 February 2022 at 12:36:06 UTC, BoQsc wrote:
 `bool nextArgumentDoesNotReachEndOfArray = i + 1 < args.length;`

 How can I declare it out of scope and reuse it in any scope 
 that has `i` and `args.length` declared?
Here is an ugly solution, just to encourage someone else to post better: ```d enum n = "i+1<args.length"; void main() { int i; string[] args; assert(!mixin(n)); args.length += 2; assert(mixin(n)); testOtherScope(); } void testOtherScope() { int i; string[] args; assert(!mixin(n)); args.length += 2; assert(mixin(n)); } ``` The problem with that solution is that it's not clean. The problem of the initial problem is to have automatic capture of `i` and `args` in any scope... Lost cause ?
Feb 12 2022
parent "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
On Sat, Feb 12, 2022 at 05:52:01PM +0000, Basile B. via Digitalmars-d-learn
wrote:
[...]
 The problem with that solution is that it's not clean.
 The problem of the initial problem is to have automatic capture of `i`
 and `args` in any scope...
 
 Lost cause ?
Lost cause, IMO. Automatic capture of arbitrary identifiers, while it seems useful at first glance, leads to all sorts of problems down the road. Consider, for example, what happens if a typo made it capture something in an outer or global scope, for example. Or if `i` and `args` happen to be defined with the wrong types. Or if somebody modified the mixin to capture something *other* than what you expected it to capture (i.e., encapsulation breakage). If you work through these unwanted cases, you eventually have to conclude that explicitly passing them as arguments is globally superior, in spite of being locally more inconvenient. T -- Век живи - век учись. А дураком помрёшь.
Feb 12 2022