如何将数字变量保存到applescript文件中?

时间:2013-07-11 14:45:12

标签: variables applescript read-write

我正在尝试创建一个简单的计数器,每次运行脚本时都会向计数中添加一个。我尝试过使用属性,但这不起作用,因为无论何时编辑脚本或关闭计算机,它都会重置。这是我从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

有了这个,我得到了错误:

  

无法将“:用户:硬件:库:脚本:应用程序:LightSpeed:CurrentProductCode.txt”转换为类型文件。

如果我在第一个“打开以访问文件”后添加“将文件设置为文件作为别名”,它会在代码中稍微进一步,但会出现另一个错误:

  

无法将“1776”变为整数类型。

现在我没有想法。我在谷歌上面搜索过没有发现任何对我有用的东西。感谢

1 个答案:

答案 0 :(得分:2)

我喜欢使用脚本对象来存储数据:

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