How can we dynamically create variable names from changing value "x" on a loop?

Sannyasin Brahmanathaswami brahma at hindu.org
Sun Nov 6 16:50:52 CET 2016


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

BR



More information about the use-livecode mailing list