1

我正在尝试制作一个简单的计数器,每次运行脚本时都会在计数中加一。我曾尝试使用一个属性,但这不起作用,因为每当编辑脚本或关闭计算机时它都会重置。这是我从这里获取的代码。

    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

有了这个我得到错误:

无法将“:Users:hardware:Library:Scripts:Applications:LightSpeed:CurrentProductCode.txt”转换为类型文件。

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

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

现在我没有想法了。我用谷歌搜索了整个地方,没有找到任何适合我的东西。谢谢

4

1 回答 1

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
于 2013-07-11T14:59:26.687 回答