2013-07-11 36 views
1

我正在试图制作一个简单的计数器,每次脚本运行时都会为计数添加一个计数器。我尝试过使用属性,但这不起作用,因为无论何时脚本被编辑或计算机关闭,它都会重置。这是我从here拿到的代码。如何将一个数字变量保存到applescript中?

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 

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

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

如果我添加“theFile设置为theFile为别名”后的第一个“开放接入theFile”它得到的代码远一点,但得到另一个错误:

Can’t make "1776" into type integer.

而现在我没有想法。我已经搜遍遍地都没有找到任何适合我的东西。由于

回答

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 
+0

真棒!谢谢。完美的作品。我知道必须有更好的方法来存储数字变量!再次感谢 –

相关问题