使用Lua检测键盘按键组合 [英] Using Lua to detect a combination of keyboard key presses
问题描述
我正在编写《魔兽世界》附加组件,我希望该附加组件能够基于按键或按键组合来执行某些功能.现在,大多数关键状态都已受保护的WoW API函数,但附加组件仍可以使用以下功能:
I'm in the middle of writing a World of Warcraft addon and I want the addon to be able to perform certain functions based on a key press or a combination of key presses. Most of the key states are protected WoW API functions now but the following are still able to be used by addons:
IsAltKeyDown()
IsControlKeyDown()
IsShiftKeyDown()
我想做的就是根据这些按键中的任何一个或按键的组合来执行功能.
What I'd like to be able to do is perform a function based on any one of those keys down or a combination there of.
这就是我正在工作的:
function KeyCombos()
total = 0
if IsShiftKeyDown() then
total = total + 1
end
if IsControlKeyDown() then
total = total + 2
end
if IsAltKeyDown() then
total = total + 4
end
end
现在我的问题不一定是关于Lua的,因为上面的函数正在起作用,因此我可以检查总计是否等于6,例如查看是否同时按下了Control和Alt.我的问题更多是算法问题.有没有更好的方法以编程方式执行此操作?
Now my question isn't necessarily about Lua, as the above function is working as I can check if total equals 6 for example to see if Control and Alt are both pressed. My question is more of an algorithmic one. Is there a better way to perform this programmaticly?
推荐答案
如果要使用表,通常情况下,保持相同的表会更好.
If you are going to use a table, in the general case it would be much better to keep the same table.
function KeyCombos()
keys = keys or {}
keys.shift = IsShiftKeyDown()
keys.control = IsControlKeyDown()
keys.alt = IsAltKeyDown()
end
或者,如果您愿意
function KeyCombos()
if not keys then
keys = {}
end
keys.shift = IsShiftKeyDown()
keys.control = IsControlKeyDown()
keys.alt = IsAltKeyDown()
end
问题中的原始示例在使用整数数学时性能更高.
The original example in the question, however, is much more performant using integer math.
但是这些示例都创建了全局变量.所以:
However these examples all create globals. So:
function GetKeyCombos()
local keys = 0
if IsShiftKeyDown() then
keys = keys + 1
end
if IsControlKeyDown() then
keys = keys + 2
end
if IsAltKeyDown() then
keys = keys + 4
end
return keys
end
会好得多.在《魔兽世界》中,所有插件都共享相同的全局环境,因此最好保持其清洁.
would be much better. In WoW all AddOns share the same global environment so its best to keep it clean.
这篇关于使用Lua检测键盘按键组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!