如何创建Applescript动态变量

问题描述 投票:0回答:3

我有一个包含一系列术语的脚本。我想根据每个术语创建变量。我试图计算用户选择每个术语的次数,并记录与术语相关的数字(也来自用户输入)。

我使用jQuery的历史让我想要做这样的事情:

set term + "_Count" to term + "_Count" + 1
set term + "_Log" to term + "_Log" + inputNum

但是,(显然)AppleScript无法使用这种语法。有没有办法将字符串连接到变量名称?

- 为了更多的参考,我试图避免列出每个术语,因为我尝试设置与每个术语相关的2个变量。当用户选择一个术语时,我现在有一个很长的If / Then语句来设置每一个。

  • 术语:“项目”
  • termCount:3次激活
  • termLog:120分钟

我一直在寻找,但没有找到任何结论我的问题。也许我只是不知道搜索的正确术语,或者我的整个方法可能不正确。任何帮助,将不胜感激。

applescript
3个回答
2
投票

你真的没有。你想要的是一个dictionary数据类型(又名“hash”,“map”,“associative array”等),它使用任意键(最常见的字符串)存储和检索值。 AS没有本机字典类型,但是对于存储简单值类型(布尔值,整数,实数,字符串),您可以通过AppleScript-ObjC桥使用Cocoa的NSMutableDictionary类:

use framework "Foundation"

set myDict to current application's NSMutableDictionary's dictionary()

myDict's setValue:32 forKey:"Bob"
myDict's setValue:48 forKey:"Sue"

(myDict's valueForKey:"Bob") as anything
--> 32

0
投票

短篇故事:

变量名称在编译时进行评估。动态变量(在运行时评估)是不可能的。


0
投票

在没有看到所有代码的情况下很难给出确切的答案,但您可以使用连接来定义新变量。

如果要将以下代码保存为应用程序,则选择的项目及其选择的次数将存储在脚本中并更新值。

同样,很难确切地确定您需要什么,但这是连接的一个示例,并定义了项目被选择的次数

property theUserChose : {"Project_1", "Project_2", "Project_3"}
property term_1_count : 0
property term_2_count : 0
property term_3_count : 0
property minutes : 120
property term : missing value

set resultValue to choose from list theUserChose ¬
    with title "Make Your Choice" OK button name ¬
    "OK" cancel button name "Cancel" without empty selection allowed

set resultValue to resultValue as string

if resultValue is item 1 of theUserChose then
    set term_1_count to term_1_count + 1
    set term to resultValue & "_" & term_1_count & "_" & minutes
else
    if resultValue is item 2 of theUserChose then
        set term_2_count to term_2_count + 1
        set term to resultValue & "_" & term_2_count & "_" & minutes
    else
        if resultValue is item 3 of theUserChose then
            set term_3_count to term_3_count + 1
            set term to resultValue & "_" & term_3_count & "_" & minutes
        end if
    end if
end if

display dialog term
© www.soinside.com 2019 - 2024. All rights reserved.