Retrieve the value of a property in a record, by addressing the property with a variable

818 Views Asked by At

Say I have a record like this:

set my_record to {song1:"Song 1", song2:"Song 2", song3:"Song 3", book1:"Book 1", book2:"Book 2", book3:"Book 3"}

By saying..

return song2 of my_record

.. I can retrieve the value of item1

Now I want to retrieve an item by addressing it with a variable

I tried something like this:

set current_song to "song" & 2
return current_song of my_record

But this returns an error.

Do I need to convert the string to another type or is what I'm trying not possible?

1

There are 1 best solutions below

3
On

Not sure what you are asking about, but at least you can do like this, to set a song from your record into a variable. If you want to change the properties, then that can be done with second level evaluation, through a run script

set  {song2:ThisSong} to  my_record 
— populates ThisSong with the contents of the field song2

Second level evaluation (untested) would be something like:

run script "set {song" & 2 & ":ThisSong} to my_record"
— uses second level evaluation to construct the field label on the fly.

Edit Here is a tested example, although I think it should be somewhat easier to perform the second level evaluation, and pass in, and out values of variables, this is the only thing I made to work.

 property mrec : {book1:"Tom Sawyer", book2:"Two twins"}
 property thisBook : missing value
 run script "set {book" & 1 & ": my thisBook} to properties of my mrec"
 log thisBook