Search code examples
variablesapplescriptread-write

How to save a number variable to file in applescript?


I am trying to make a simple counter that adds one to the count every time the script is run. I have tried using a property but that doesn't work because it resets whenever the script is edited or the computer is turned off. Here is the code I have that I took from here.

    set theFile to ":Users:hardware:Library:Scripts:Applications:LightSpeed:" & "CurrentProductCode.txt"

open for access theFile
set fileContents to read theFile
close access theFile

set counter to fileContents as integer

on add_leading_zeros(counter, max_leading_zeros)
    set the threshold_number to (10 ^ max_leading_zeros) as integer
    if counter is less than the threshold_number then
        set the leading_zeros to ""
        set the digit_count to the length of ((counter div 1) as string)
        set the character_count to (max_leading_zeros + 1) - digit_count
        repeat character_count times
            set the leading_zeros to (the leading_zeros & "0") as string
        end repeat
        return (leading_zeros & (counter as text)) as string
    else
        return counter as text
    end if
end add_leading_zeros

add_leading_zeros(counter, 6)


open for access newFile with write permission
set eof of newFile to 0
write counter + 1 to newFile
close access newFile

With this I get the error:

Can’t make ":Users:hardware:Library:Scripts:Applications:LightSpeed:CurrentProductCode.txt" into type file.

If I add "set theFile to theFile as alias" after the first "open for access theFile" it gets a little further in the code, but gets another error:

Can’t make "1776" into type integer.

And now I am out of ideas. I have googled all over the place haven't found anything that works for me. Thanks


Solution

  • I like to use script objects to store data:

    set thePath to (path to desktop as text) & "myData.scpt"
    
    script theData
        property Counter : missing value
    end script
    
    try
        set theData to load script file thePath
    on error
        -- On first run, set the initial value of the variable
        set theData's Counter to 0
    end try
    
    --Increment the variable by 1
    set theData's Counter to (theData's Counter) + 1
    
    -- save your changes
    store script theData in file thePath replacing yes
    return theData's Counter