constants - 有没有办法在 Applescript 中有常量?
问题描述
我目前正在开发一个模仿 pythonmath
模块的 Applescript 数学库。pythonmath
模块有一些常量,比如欧拉数等。目前,您可以执行以下操作:
set math to script "Math"
log math's E -- logs (*2.718281828459*)
set math's E to 10
log math's E -- logs (*10*)
因此,我尝试搜索 Applescript 常量,并遇到了官方文档,其中指出,You cannot define constants in scripts; constants can be defined only by applications and by AppleScript.
是否有一个聪明的解决方法,或者我必须为这种事情编写一个 .sdef 文件?
编辑:
我现在也试过这个:
log pi -- logs (*3.14159265359*)
set pi to 10
log pi -- logs (*10*)
pi
是一个 Applescript 常量。如果您再次运行脚本而不再次编译,它看起来像这样:
log pi -- logs (*10*)
set pi to 10
log pi -- logs (*10*)
我不想模仿这种行为,但更想模仿其他常量(如ask
, yes
,no
等)的行为,即使您尝试将它们设置为它们自己也会抱怨。
解决方案
无法在 AppleScript 中显式定义常量。根据您要实现的目标,三种方法可能就足够了。
如果您在库中使用脚本定义 (sdef),则可以添加枚举来定义要保留的术语,然后在代码中按大小写处理它们。例如,如果您想为术语 'tau'、'gamma' 和 'lambda' 分配常量值,您可以像这样定义一个枚举:
<enumeration name="Constants" code="CVal" description="defined constant values.">
<enumerator name="tau" code="tau&" description="tau constant."/>
<enumerator name="gamma" code="gam&" description="gamma constant."/>
<enumerator name="lambda" code="lmd!" description="lambda constant."/>
</enumeration>
然后在代码中有一个处理程序来解决它们,并在需要时调用它:
to resolveConstant(cnst)
if cnst is tau then
return pi/2
else if cnst is gamma then
return 17.4683
else if cnst is lambda then
return "wallabies forever"
else
return missing value
end
end resolveConstant
为每个常量创建处理程序,并将它们作为函数调用:
on tau()
return pi/2
end tau
set x to 2 * tau() * 3^2 -- x = 28.2743
如果你想要真正的常量,你将不得不离开脚本库并编写一个不露面的后台应用程序(如系统事件或图像事件)。从最终用户的角度来看,这不会有太大的不同,除了他们必须授权让应用程序运行之外,但这可能意味着您最终需要大量增加劳动力。
推荐阅读
- javascript - 如果文本区域中写入了某个单词,则替换 url
- python - AttributeError:无法设置属性,
- mysql - 将已排序分区中的行划分为特定数量的组。[MySQL]
- mysql - 警告:1265 第 1 行的“价格”列的数据被截断
- javascript - 如何将项目推送到作为数组的 es6 Map 对象值中?
- php - FPDF 无法通过 sql 连接加载 PDF 文档
- javascript - javascript中链接方法的复杂性
- excel - 如何将数据粘贴到右侧的下一个空单元格中?
- javascript - 当我单击按钮时,没有任何反应
- javascript - 返回承诺对象时使用`Async`关键字