Save and recall a selection of variables

Hey Kevin,

variableDataSet is just a variable that you're looking at in the Script Editor. It is not the final result of a script that saves a data-set.

You already have your list of variable names in variableNameSet.

So, one way to save those items is using a plist file like we're discussing in this thread:

Saving Keyboard Maestro variables in a Plist file

Another way is to use a simple script-object:

---------------------------------------------------------------------------------
# Data Storage with a simple script object.
---------------------------------------------------------------------------------
set savedPrefsFolder to alias ((path to home folder as text) & "test_directory:Saved_Preference_Files:")
---------------------------------------------------------------------------------
script saveDataScriptObject
  property savedVariableNameSet : {}
  property savedVariableDataSet : {}
end script
---------------------------------------------------------------------------------
set variableNameSet to items 1 thru -2 of {¬
  "ENV_PATH", ¬
  "makeFoldersDest", ¬
  "makeFoldersSrc", ¬
  "Ren__Find", ¬
  "Ren__Repl", ¬
  "ReplyUsingRulesOutput", ¬
  "X", ¬
  "Y", ¬
  ""}

set variableDataSet to {}

tell application "Keyboard Maestro Engine"
  repeat with varName in variableNameSet
    set end of variableDataSet to getvariable varName
  end repeat
end tell

set saveDataScriptObject's savedVariableNameSet to variableNameSet
set saveDataScriptObject's savedVariableDataSet to variableDataSet

store script saveDataScriptObject in ((savedPrefsFolder as text) & "savedPrefs01.scpt") with replacing
-------------------------------------------------------------------------------------------

And this is how we get the data back.

---------------------------------------------------------------------------------
# Retrieval of Keyboard Maestro variable names and data from saved prefs file.
---------------------------------------------------------------------------------
set myPrefs to load script alias ((path to home folder as text) & "test_directory:Saved_Preference_Files:savedPrefs01.scpt")

tell myPrefs
  set variableNameSet to its savedVariableNameSet
  set variableDataSet to its savedVariableDataSet
end tell

---------------------------------------------------------------------------------
# Restoration in Keyboard Maestro
---------------------------------------------------------------------------------
tell application "Keyboard Maestro Engine"
  repeat with i from 1 to (length of variableNameSet)
    setvariable (item i of variableNameSet) to (item i of variableDataSet)
  end repeat
end tell
---------------------------------------------------------------------------------

This method is very fast.

-Chris

3 Likes