AutoHotkey中字符串类型变量比较失效问题排查
AutoHotkey变量比较失效问题分析与解决
问题根源
你脚本里的变量赋值犯了一个关键错误:
- 初始化时用表达式赋值
global lastCommand := "q",此时变量存储的是不带引号的字符串q。 - 但热键里的赋值用了传统赋值运算符
lastCommand = "q",这种写法会把双引号也当成变量值的一部分,导致lastCommand实际存储的是带引号的"q"。 - 后续比较时,
if (lastCommand == "w")是和不带引号的w对比,而变量里存的是"w",自然不匹配,所以永远执行else分支。
修正方案
有两种方式可以修复:
- 统一使用表达式赋值
:=(推荐,和初始化逻辑保持一致) - 使用传统赋值
=时,去掉右侧的双引号
修正后的完整脚本
方案1:统一用表达式赋值
#SingleInstance Force CoordMode, Mouse, Client CoordMode, Pixel, Client SendMode Input SetDefaultMouseSpeed, 0 global lastCommand := "q" q:: if (lastCommand == "w") { Msgbox last command was w } else { Msgbox % lastCommand } lastCommand := "q" return w:: if (lastCommand == "q") { Msgbox last command was q } else { Msgbox % lastCommand } lastcommand := "w" return
方案2:传统赋值去掉引号
#SingleInstance Force CoordMode, Mouse, Client CoordMode, Pixel, Client SendMode Input SetDefaultMouseSpeed, 0 global lastCommand := "q" q:: if (lastCommand == "w") { Msgbox last command was w } else { Msgbox % lastCommand } lastCommand = q return w:: if (lastCommand == "q") { Msgbox last command was q } else { Msgbox % lastCommand } lastcommand = w return
内容的提问来源于stack exchange,提问作者james
相关产品推荐
相关产品推荐

