Dynamic variable names test

Started by cssyphus, May 15, 2024, 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 





kdmoyers

I use it to return a SQL query results as an array, with constants already defined for the column names, so I don't have to think about what order they are in.  Very handy.

but yes, use it very sparingly, because it can be the source of impossible-to-kill bugs that will eat weeks of your life.  Be doubly cautious about using it inside any kind of loop.
The mind is everything; What you think, you become.

spl

Quote from: kdmoyers on May 16, 2024, 05:16:58 AMbut yes, use it very sparingly, because it can be the source of impossible-to-kill bugs that will eat weeks of your life.  Be doubly cautious about using it inside any kind of loop.

With that in mind, WB's Execute command can be useful [used it for years for ADO streams to place Excel templates into  Access or SQL Server binary fields]. Great for creating vars:values within a loop, until it messes up :)
Stan - formerly stanl [ex-Pundit]

spl

For example:
list = "Stan,Bob,Chuck,Roy,Jennifer,Arial,Tony"
For i=1 to ItemCount(list,",")
   v= "name = '":ItemExtract(i,list,","):"'"
   Execute %v%
   Display(1,"My Name Is...",name)
Next
Stan - formerly stanl [ex-Pundit]