MacOS – Source code to string in variable

applescriptmacos

In AppleScript Editor i can see that source_code has script content but row 2 fails for some reason.

set source_code to load script (POSIX file "/path/to/script.scpt")
word 2 of source_code

This don't work. I try to read AppleScript files to variable.

I don't try to run this loaded code but i need to get it as string.


It seems to fail because source_code is «script» not string. How this can be fixed? Thanks

set source_code to load script (POSIX file "/path/to/script.scpt")
word 2 of (source_code as string) -->error "Can’t make «script» into type string." number -1700 from «script» to string
word 2 of source_code -->error "Can’t get word 2." number -1728 from word 2

Best Answer

The load script command loads a script as an object to be run, rather than as text to read or manipulate.

If you want to access the actual text of your script, you can use osadecompile:

do shell script "osadecompile ~/Library/Scripts/test.scpt"
word 2 of result

Compiled scripts saved with AppleScript Editor usually have LF line endings in strings but CR line endings in other places. osadecompile converts all line endings to LF. do shell script converts line endings to CR unless you add a without altering line endings specifier.