首页 > 解决方案 > 如何动态设置此 IniRead?

问题描述

卡了一段时间,希望有经验的人能帮帮我...

现在我正在读三遍这样的 Ini,但希望从长远来看动态地改进我的代码。

IniRead, Alert_price_low, %TrackerFile%, Item, Alert_price_low
IniRead, Alert_price_high, %TrackerFile%, Item, Alert_price_high
IniRead, Alert_checkbox, %TrackerFile%, Item, Alert_checkbox

我在下面创建了这个函数,试图动态读取它,但没有返回任何东西......

FindIniSettings(TrackerFile, Alert_checkbox)

FindIniSettings(TrackerFile, x){
    x := IniRead, %x%, TrackerFile, Item, %x%
    return x
}

我的 Ini 文件内容如何:

[Item]
Alert_price_low=777
Alert_price_high=999
Alert_checkbox=1

谢谢!

标签: autohotkey

解决方案


这里的问题几乎与新表达式语法的使用有关。
似乎您一直在使用已弃用的遗留语法,而函数并不在其中。

所以第一个问题在
FindIniSettings(TrackerFile, Alert_checkbox)
这里你不是在遗留语法,所以要指定你引用它们的字符串。
FindIniSettings(TrackerFile, "Alert_checkbox")
(我假设TrackerFile这里是一个包含一些iniFileNameOrPath.ini字符串的变量)
另外,你没有在任何地方存储这个函数的返回值。

第二个问题在这里
x := IniRead, %x%, TrackerFile, Item, %x%
首先,命令是遗留的,它们不会返回那样的值。
您不能使用:=运算符来获取返回值。
它们仅通过将输出写入请求的变量来返回值,该变量将在命令的第一个参数中指定。
您指定将输出变量命名为包含的任何x内容。这不好,因为您不可能知道在运行时输出变量将是什么(没有一些不必要的额外技巧)。
此外,将输出命名为与输入键相同会非常令人困惑。不过,那会奏效。

所以那里有两个问题,:=第一个%x%,还有一些问题就在这里:
, TrackerFile,
命令是遗留的,如上所述,它们在每个参数中专门使用遗留语法(除非文档中另有说明)。
因此,您传递的是文字文本“TrackerFile”,而不是应该存储在名为TrackerFile.
在旧语法中,您可以通过将变量包裹在 中来引用变量的内容%%,就像您之前所做的那样。也许你只是忘记了这里。
但实际上,我建议您尝试习惯放弃旧语法。所以你可以/应该做的,是从一个参数开始%后跟一个空格。这使得 ahk 解释该参数上的表达式,而不是使用旧语法。在现代表达式语法中,您只需键入变量名即可引用变量。不需要愚蠢%%的。


所以这是你最终应该得到的固定脚本。我使这个示例完全免费的旧语法作为演示:

TrackerFile := "test.ini"

returnValueOfThisFunction := FindIniSettings(TrackerFile, "Alert_price_low")
MsgBox, % "Yay, the function returned a value for us:`n" returnValueOfThisFunction

return


FindIniSettings(TrackerFile, key)
{
    ;even specified the string "Item" explicitly as a string
    ;this is not needed, but it just looks right to me
    ;I wouldn't want to specify a legacy parameter there
    ;in the middle of all this
    IniRead, output, % TrackerFile, % "Item", % key
    MsgBox, % "Now the variable named ""output"" contains the result of the above command (" output ").`nWe can now return it to the caller."
    return output
}

所以,是的,几乎只是理解遗留语法与表达式语法的问题。
您可以在这里%%阅读我之前关于vs用法的答案%
这是 AHK 文档上关于脚本语言和传统与现代表达的好页面


推荐阅读