r/ComputerCraft • u/KarmyDev • Feb 07 '23
Fixed Double Click script for those who struggle with the one from forums
I made some tweaks to the script found on this forum because it wasn't working for me.
Here it is:
Use it by require("")ing the file with the code below, and replace your os.pullEvent() with os_customPullEvent(). It pulls same events as before except it adds mouse_doubleclick event.
local _dctimer = nil
local _dcinterval = 0.25
local _captured = false
function lib_customPullEvent(_type)
local _event = {os.pullEvent()}
if _event[1] == "mouse_click" then
if _captured then
_event[1] = "mouse_doubleclick"
_captured = false
return unpack(_event)
elseif not (_dctimer == nil) and not _captured then
_event[1] = "mouse_doubleclick"
--No consecutive double-clicks.
_captured = true
elseif _dctimer == nil and not _captured then
--Prepare for double click
_dctimer = os.startTimer(_dcinterval)
end
return unpack(_event)
elseif _event[1] == "timer" and _event[2] == _dctimer then
_dctimer = nil
_captured = false
else
if _dctimer then _captured = true end
return unpack(_event)
end
end
--Sets the length of the interval for a doubleclick
setDoubleClickInterval = function(_val)
if _val and type(_val) == "number" and
_val > 0 then
_dcinterval = _val
end
end1
u/fatboychummy Feb 07 '23 edited Feb 07 '23
Alright, wrote out a better thing.
... Did it on my phone so I can't test that it actually works, but it should work. Hopefully.
Notable changes:
Event pull doesn't always return the correct event that the user requested. An event pull should return either the event filter requested no matter what, or in the case no filter was supplied, any event. That is fixed.
Event pull may incorrectly assume some clicks are double-clicks when they are not (no reference to
os.clock,os.time, oros.epochthere), that is fixed here.Event pull may discard event arguments. Swapped to using
table.packandtable.unpackinstead of{}andunpack.Event pull may return
nilevents. This is because you don't loop, then when you receive your own timer event you return nothing. I don't use timer events in my code (and have a different, more "return-safe" structure), so we shouldn't run into this issue.Added Sumneko LLS annotations.
Use
cc.expectmodule for argument correctness.Modern Lua practices for
required modules.
1
u/fatboychummy Feb 07 '23
There's a lot of issues with this... One of which being that if something else eats the timer event (say, a
sleep()call), it will assume that the time has not yet passed and the first click from that point on will be a double click. Even if it was 30 seconds later.I'm going to quickly make a more robust version of this which also takes that into account and uses more modern coding practices. I'll be back!