Writing and reading back variables into a script (preferences)

I want to know how I may be able to write variable information from a script into a preferences file. I want to then be able to load that file back into the script while maintaining variable names. I am aware of being able to write variables out as a list and then loading them back in… but that then relies on the script knowing the order of information in the preferences file.

Probably not the best way but I’ve used it in the past


set tempFile to "/path/to/file/prefs.txt"
set d to "Dallas"
set f to "Fred"

--Write to file
do shell script "echo ''>" & quoted form of tempFile
do shell script "echo VariableValueD:" & d & ">>" & quoted form of tempFile
do shell script "echo VariableValueF:" & f & ">>" & quoted form of tempFile

--Null the values
set d to null
set f to null


--Get the values back
set d to do shell script "cat " & quoted form of tempFile & "| grep 'VariableValueD:' | awk -FVariableValueD: '{print $2}'"
set f to do shell script "cat " & quoted form of tempFile & "| grep 'VariableValueF:' | awk -FVariableValueF: '{print $2}'"

return d & " " & f


Dallas

Perhaps something like this? You can change the order of the list in anything you want. You just type foo of barList to get the value of the item with the foo-name of the barList?

writePerson("Testing", (path to desktop))
readAndDisplayPerson("Testing", (path to desktop))

on writePerson(fileName, fileContainer)
	set myList to {firstName:"Joe", lastName:"Johnson", streetName:"Main Street", streetNumber:35, city:"Capital City"}
	
	tell application "Finder" to if not (exists file fileName of fileContainer) then make new file at fileContainer with properties {name:fileName}
	
	tell application "Finder" to set fileToWrite to file fileName of fileContainer as alias
	
	set OA to open for access fileToWrite with write permission
	write myList to OA starting at 0 as list
	close access OA
end writePerson

on readAndDisplayPerson(fileName, fileContainer)
	tell application "Finder" to set fileToRead to file fileName of fileContainer as alias
	set myData to (read fileToRead as list)
	log myData
	
	display dialog ("Hello " & (firstName of item 1 of myData) & " " & (lastName of item 1 of myData) & " from " & (city of item 1 of myData)) buttons "OK" default button 1
end readAndDisplayPerson

Hope it helps,
ief2