Coerce keys and values into a record

Well this is obviously not new and can be done by using external applications or ASObjC.

set theKeys to {"Hello world!", "B", "name", "D"}
set theValues to {true, current date, "hello", 1}

createUserDefinedRecord(theKeys, theValues)

on createUserDefinedRecord(theKeys, theValues)
	-- Remove keys that are not strings
	set theKeys to every text of theKeys
	-- If there are more keys than values then stop
	if (count of theKeys) > (count of theValues) then return missing value
	
	-- Create a list containing keys subsequently followed by it's associated value
	set rawList to {}
	repeat with i from 1 to count theKeys
		set end of rawList to item i of theKeys
		set end of rawList to item i of theValues
	end repeat
	
	-- Create a record who is similar to records containing only user defined keys in AppleEvents
	set rawRecord to {«class usrf»:rawList}
	
	-- A script retuning the same value as given to force coercion between AppleEvent and AppleScript later
	script x
		on run argv
			return item 1 of argv
		end run
	end script
	
	-- We'll use run script, osax command, so rawRecord is handles by the
	-- AppleEvent manager whose value is given back in the same 
	-- format as records containing user defined keys. AppleScript will coerce
	-- the list in a proper way and make the coercion for us.
	return run script x with parameters {rawRecord}
end createUserDefinedRecord

I was just cleaning up an old script I have been using for checking initialization files, the handler was used in a small library to edit initialization files. I thought this way of making records could be interested for others here as well. There is however one flaw or bug, normally keys has to be unique, this will allow the same keys in a single record. When the value is called by it’s key, only the first value will be returned. This was for my own usage more or less a feature instead of a bug :slight_smile:

A shorter way to convert the “raw record” to a real one ” similar to a hack which used to appear on the AppleScript-Users list in days of yore ” is:

-- Create a record who is similar to records containing only user defined keys in AppleEvents
return «class seld» of (record {«class usrf»:rawList} as record)

The ‘record’ before ‘{«class usrf»:rawList}’ is not only weird, but can be almost any AppleScript class name!

return «class seld» of (Monday {«class usrf»:rawList} as record)
return «class seld» of (degrees Fahrenheit {«class usrf»:rawList} as record)

:slight_smile:

Thanks Nigel,

As an former AppleScript-list user myself I can’t remember the raw object specifier coercion and then getting the item from the record. Even if it’s slower it does indeed look better :cool:

Fun things are worth lingering over. :wink: