Dynamic variable names test

Started by cssyphus, Today at 06:08:56 AM

Previous topic - Next topic

cssyphus

I could not believe this worked as well as it did...

_test1 = `bob`
_test2 = `sam`
_test3 = `ann`

for _n = 1 to 7
   _var = `_test%_n%`
   if isDefined(%_var%) ;THIS WORKS!
      display(1, ``, %_var%) ;THIS WORKS!
   endif
   ;display(1, ``, _test%_n%) ;THIS ALSO WORKS!
next

This allows for:

* creating dynamic variable names on the fly
* dynamically creating new var names in a loop, using the loop counter in the variable name
* testing for the existence of dynamically-constructed variable names

WinBatch: every new version is worth every penny.

JTaylor

Substitution has been around forever.   It can be your best friend or your worst enemy.  Keep in mind that if you do something like.

   _var = `_test%_n%`

and _n doesn't exist, you will receive no error.

It has always been highly recommended to only use it when absolutely necessary as problems can be hard to find.

That said, it can do awesome things, as you have noted.   One use I put it to is to retrieve settings from a database for one of my applications, which has hundreds, and initialize them at application start.  Can save them the same way.  It turns several hundred of lines of code into 30 or so.  It is also very useful for making SQL Scripts readable instead of having a ton of extra concatenation and quote symbols.

Jim