Roblox ATM按键异常:Enter/Back按钮触发事件重复执行10次
问题分析与解决方案
问题根源
你把enter、back、reset这三个按钮的MouseClick事件绑定,放在了遍历10个数字按钮的for循环里。每循环一次就给这三个按钮绑定一次事件,最终每个按钮都被重复绑定了10次——这就是点击时函数重复执行10次的原因。
比如点击back按钮时,10个绑定的函数会依次执行,导致多次打印索引、多次删除输入内容;点击enter时,第一次执行会清空input数组,后面9次调用keyPressed时input已经是空的,返回空字符串,自然和正确PIN对比失败。
修正后的代码
把非数字按钮的事件绑定移到for循环外面,只绑定一次即可:
local atmScreen = workspace.ATM.SurfaceGui.Frame.Info local input = {} local enterPressed = false local folder = workspace.ATM.NumberButtons local insertCard = workspace.ATM.InsertCard.ClickDetector local back = workspace.ATM.Back.ClickDetector local reset = workspace.ATM.Reset.ClickDetector local enter = workspace.ATM.Enter.ClickDetector -- Pin local pin = "1234" function keypad() -- 仅遍历数字按钮,绑定数字按键事件 for i, v in pairs(folder:GetChildren()) do v.ClickDetector.MouseClick:Connect(function() table.insert(input, i) keyPressed(input) end) end -- 以下事件绑定移到循环外,只执行一次 enter.MouseClick:Connect(function() enterPressed = true local x = keyPressed(input) print(x) table.clear(input) enterPressed = false if x == pin then atmScreen.Text = "Pin Correct!" wait(1) else atmScreen.Text = "Pin Incorrect! Please reenter pin!" end end) reset.MouseClick:Connect(function() table.clear(input) keyPressed(input) end) back.MouseClick:Connect(function() local index = table.maxn(input) print(index) table.remove(input, index) keyPressed(input) end) end function keyPressed(input) local output = "" for _, num in pairs(input) do output = output .. num end atmScreen.Text = output if enterPressed == true then return output end end
额外优化建议
table.maxn属于过时API,推荐用#input获取数组长度,同时增加空数组判断避免报错:back.MouseClick:Connect(function() local index = #input if index > 0 then print(index) table.remove(input, index) keyPressed(input) end end)pairs遍历顺序不固定,若数字按钮命名为Button0-Button9这类格式,建议通过名称提取真实数字,避免输入顺序错乱:for _, v in pairs(folder:GetChildren()) do local num = tonumber(v.Name:match("%d+")) v.ClickDetector.MouseClick:Connect(function() table.insert(input, num) keyPressed(input) end) end
内容的提问来源于stack exchange,提问作者Wild Alex
相关产品推荐
相关产品推荐

