How can we dynamically create variable names from changing value "x" on a loop?
benr_mc at cogapp.com
Mon Nov 7 13:37:49 CET 2016
It's easy to dynamically create and set the values of variables, using the
"do" command, e.g.:
do format("put tValue into %s", tVarName)
I do lots of work with TSV files, which have a first row of field names, and
for years have used a function like this to create local variables, named for
each column, with the index to that column as their value
do makeAccessVars("vi", line 1 of tTSVdata)
where the function creates a script doing essentially the above for all the
field names, with a prefix (and taking care of spaces etc), which I then "do"
in the individual procedure so that the variables are declared local to the
(Re Mike and Mark's comments, if it's a small thing I'll use an array; but for
large quantities of data - I'm often dealing with very large files, and after
calling this function will loop over tens or hundreds of thousands of rows
using the variables - I feel the need for speed outweighs the simplicity.)
A minor isse with this is that it doesn't play nice with explicitVars: in
order to nicely compile a script that invokes this function and then goes on
to, for example,
repeat for each line tRec in tTSVdata
doSomething item viUserID of tRec, item viUserName of tRec
I have to have declared viUserID, and viUserName in the handler.
On 06/11/2016 15:50, Sannyasin Brahmanathaswami wrote:
> Given this scenario:
> We fetch a preference array from some json on disk
> We want to insert the key-values into separate discrete local vars in the stack script
> function getUserPreferences
> # the following function fetches an object in a JSON file:
> put getPref ("preferences/modules/color-meditation") into aColorMedPrefs
> # aColorMedPrefs now appears in variable watcher with keys
> # aColorMedPrefs["BreathCount"] # value = 5
> # aColorMedPrefs["BreathPace,"] # value = 1
> # aColorMedPrefs["Cycles "] # value = 2
> # aColorMedPrefs["AudioOn"] # value = "true"
> # we want to pass each to a discrete local:
> # sBreathCount,sBreathPace,sCycles,sAudioOn
> repeat for each key x in aColorMedPrefs
> put "s" & x into tNextPref
> put aColorMedPrefs[x] into tNextPref
> put tNextPref & comma after tSettings
> end repeat
> return tSettings
> # result: "5,1,2,true" i.e. the values
> # But what we really want to do was insert those values in the local vars on each iteration.
> return (sBreathCount,sBreathPace,sCycles,sAudioOn) # would also return
> "5,1,2,true" # but we get ",,," i.e now values.
> end getUserPreferences
> i.e. how do we dynamically create/name/instantiate variables & set their values from values in a loop?
> it begs for some syntax like
> create var ("s" & x); put x into the last var
> use-livecode mailing list
> use-livecode at lists.runrev.com
> Please visit this url to subscribe, unsubscribe and manage your subscription preferences:
More information about the use-livecode