我有以下delayed
函数,在每个按钮按下后500毫秒被调用。
function M.delayed1()
for i = 1, #presses do
if presses[i].num == 1 then
presses[i].holdMode = true
presses[i].shouldUntrigger = false
return
end
end
end
function M.delayed2()
for i = 1, #presses do
if presses[i].num == 2 then
presses[i].holdMode = true
presses[i].shouldUntrigger = false
return
end
end
end
function M.delayed3()
for i = 1, #presses do
if presses[i].num == 3 then
presses[i].holdMode = true
presses[i].shouldUntrigger = false
return
end
end
end
function M.delayed4()
for i = 1, #presses do
if presses[i].num == 4 then
presses[i].holdMode = true
presses[i].shouldUntrigger = false
return
end
end
end
实际上,代码要长得多,因为我总共使用了64个按钮。 我想知道在这种情况下是否有可能减少Lua中的代码量。
答案 0 :(得分:4)
您可以循环设置M
的表项,并为closures分配循环索引作为上限值。
local M = {}
for n = 1, 64 do
M["delayed" .. tostring(n)] = function()
for i = 1, #presses do
if presses[i].num == n then
presses[i].holdMode = true
presses[i].shouldUntrigger = false
return
end
end
end
end
答案 1 :(得分:0)
@Henri有您要的;但是我不知道为什么首先要创建64个函数副本?它们似乎都遵循相同的逻辑,那么为什么不使用单个功能来接收带有印刷机编号的参数呢?函数定义看起来像...
local function delayed(presses_array, press_num)
for id, press in ipairs(presses_array) do
if press.num == press_num then
press.holdMode = true
press.shouldUntrigger = false
break
end
end
end