2013-07-11 59 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

真棒!謝謝。完美的作品。我知道必須有更好的方法來存儲數字變量!再次感謝 –

相關問題