Advertisement
fatboychummy

CC - DoubleClick

Feb 7th, 2023
1,011
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.50 KB | None | 0 0
  1. local expect = require "cc.expect".expect
  2.  
  3. local click_out = 0
  4. local timeout = 250
  5.  
  6. local dc = {}
  7.  
  8. --- Check if the filter is valid to return the event.
  9. ---@param got string? The actual event.
  10. ---@param filter string? The filter given.
  11. ---@retutn boolean valid The validity of the event.
  12. local function check_filter(got, filter)
  13.   return not filter or filter == got
  14. end
  15.  
  16. --- Pull an event, listening gor double-clicks.
  17. ---@param filter string? The event name, or any event.
  18. ---@return string event_name The event name.
  19. ---@return any ... Event arguments.
  20. function dc.pull(filter)
  21.   expect(1, filter, "string", "nil")
  22.   while true do
  23.     local event = table.pack(os.pullEvent())
  24.  
  25.     if event[1] == "mouse_click" then
  26.       local current = os.epoch "utc"
  27.  
  28.       -- if we passed the timeout time (single click)
  29.       if current > click_out then
  30.         -- calculate the next timeout time
  31.         click_out = current + timeout
  32.       else
  33.         -- Double click! Change the event type
  34.         event[1] = "mouse_double_click"
  35.  
  36.         -- Also reset the double-click timer.
  37.         -- Next click will start the timer, click after that will be double again.
  38.         click_out = 0
  39.       end
  40.     end
  41.  
  42.     if check_filter(event[1], filter) then
  43.       return table.unpack(event, 1, event.n)
  44.     end
  45.   end
  46. end
  47.  
  48. --- Sets the length of the interval for a doubleclick
  49. ---@param n number The timeout, in milliseconds.
  50. function dc.setTimeout(n)
  51.   expect(1, n, "number")
  52.  
  53.   timeout = n
  54. end
  55.  
  56. return dc
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement