2013-07-11 3 views
1

J'essaye de faire un compteur simple qui ajoute un au compte chaque fois que le manuscrit est exécuté. J'ai essayé d'utiliser une propriété, mais cela ne fonctionne pas car elle se réinitialise chaque fois que le script est modifié ou que l'ordinateur est éteint. Voici le code que j'ai pris de here.Comment enregistrer une variable numérique dans un fichier dans 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 

Avec cela, j'obtiens l'erreur:

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

Si j'ajouter « set theFile à theFile alias » après la première « ouverte pour l'accès theFile » il obtient un peu plus loin dans le code, mais obtient une autre erreur:

Can’t make "1776" into type integer.

Et maintenant je suis à court d'idées. J'ai googlé partout, je n'ai rien trouvé qui fonctionne pour moi. Merci

Répondre

2

J'aime utiliser des objets script pour stocker des données:

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

Impressionnant! Merci. Fonctionne parfaitement. Je savais qu'il devait y avoir une meilleure façon de stocker une variable numérique! Merci encore –

Questions connexes