I have a text file storing info I want to load into a table. Each line corresponds to exactly one data cell in one row. I load everything into a list and then use “append” to get the list into the data source.
Some of the data cells are boolean, so currently I still have to do a repeat loop test to change the textual “false” or “true” into a boolean false or true value for that data cell.
Question: Is there a way to reformat the textual “false” or “true” so that when “read” command loads the data into a list, the type coercion is automatically done? (so I won’t need to go into the list one item a time to change the textual representation into one of the right type)
AppleScript has the ability to coerce strings to boolean objects, and vice versa. Just return the field ‘as text’ or ‘as boolean’ as required:
set myBool to "true"
return myBool as boolean
set myBool to true
return myBool as text
Note that in the first line ‘myBool’ is a either a string or a boolean object set to true. The result is a string/text object “true” or a boolean true as appropriate. The same hold true (no pun intended) for false boolean objects.
Thanks but the problem of the usual coercion syntax is that it can’t be done to a certain elements of a list. For example, if the said file has this format:
this is row 1
this is row 2
Each row has two columns: the first is one of boolean and the second is one of string. Using the following code to read in the data as a list:
set theFN to "data.txt"
set tableData to (read theFN using delimiter return)
close access theFN
I’ll get a list of strings. Then I need to have a repeat loop to change each “true” or “false” into boolean before I can “append” a data source with the list “tableData”. I’d like to find a direct way to read in the file and when I’m done with it, the odd-numbered elements are already in boolean.
The motivation of this is try not to use any repeat loop to improve speed of table loading.
Using this method, you’re going to have to loop though every item and coerce the string to a boolean. The key to skipping this and doing it all in one step is to either use user defaults to store the data or write the data to a file using Standard Additions read/write commands but write the data as a list of native AppleScript data classes (strings, booleans, lists, etc), instead of just lists (I’ve detailed this on the board many times).