代码之家  ›  专栏  ›  技术社区  ›  alipica

如何创建Applescript动态变量

  •  0
  • alipica  · 技术社区  · 7 年前

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

    我的jQuery历史让我想做如下事情:

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

    然而,(显然)这种语法在AppleScript中是不可能的。有没有办法将字符串连接到变量名上?

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

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

    我一直在到处寻找,但没有找到任何关于我的问题的结论。也许我只是不知道合适的搜索词,或者我的整个方法都不正确。任何帮助都将不胜感激。

    3 回复  |  直到 7 年前
        1
  •  4
  •   has    7 年前

    你真的没有。你想要的是 dictionary 数据类型(又名“哈希”、“映射”、“关联数组”等),使用任意键(最常见的字符串)存储和检索值。AS没有本机字典类型,但要存储简单的值类型(布尔、整数、实数、字符串),可以使用Cocoas NSMutableDictionary 通过AppleScript ObjC桥初始化:

    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
    
        2
  •  0
  •   vadian    7 年前

    短篇故事:

    变量名在编译时计算。不可能使用动态变量(在运行时计算)。

        3
  •  0
  •   wch1zpink    7 年前

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

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

    同样,很难准确指出您需要什么,但这是一个串联的示例,可以定义一个项目被选择了多少次

    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