This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
ThePH's profile picture

Mouse API

Started by ThePH, 14 April 2013 - 08:41 AM
ThePH #1
Posted 14 April 2013 - 10:41 AM
Hey guys, I needed to make my flexibleUI API compatible (sorta) with basic computers with no mouse support, so here is the result: a silly API that allows you to use mouse click (left click only for now).
There is no need for screens as of yet.
The use is [ui name.]pullEvent([filter]) and uses arrow key and enter for clicking.
Note this is a WIP API, and I will gladly improve it if it is used, suggestions are welcome ^^

Enjoy :)/>


function pullEvent(filter)
local xx, yy = term.getCursorPos()
local event = {}
local w, h = term.getSize()
local nKeys = {200, 203, 205, 208, 28}
local sKeys = {'UP', 'LEFT', 'RIGHT', 'DOWN', 'LCLICK'}
local x, y = math.floor(w/2), math.floor(h/2)
filter = filter or 'none'
term.setCursorBlink(true)
local function inTable(tbl, item)
  for key, value in pairs(tbl) do
   if value == item then
    return key
   end
  end
  return 0
end
while true do
  term.setCursorPos(x, y)
  local ev, p1, p2, p3 = os.pullEvent()
  local it = inTable(nKeys, tonumber(p1))
  if ev == 'key' and it ~= 0 then
   local k = sKeys[it]
   if k == 'UP' and y > 1 then
    y = y - 1
   elseif k == 'DOWN' and y < h then
    y = y + 1
   elseif k == 'LEFT' and x > 1 then
    x = x - 1
   elseif k == 'RIGHT' and x < w then
    x = x + 1
   elseif k == 'LCLICK' then
    event = {'mouse_click', 1, x, y}
    break
   end
  elseif ev == filter then
   event = {ev, p1, p2, p3}
   break
  end
end
term.setCursorBlink(false)
term.setCursorPos(xx, yy)
return unpack(event)
end

Small script to test with :


term.clear()
term.setCursorPos(1, 1)
while true do
_, _, x, y = pullEvent()
print(x, ':', y)
end
Sariaz #2
Posted 18 April 2013 - 07:45 PM
If you don't put in a filter it looks like you set filter to none. Since your directly comparing filter to your event and there is not event named none I don't think it would work. Have you tried not giving it a filter and see if it returns like a timer event?
ThePH #3
Posted 20 April 2013 - 03:44 AM
Be aware that my function does NOT replace os.pullEvent(), you must only use it when you need a mouse input (no filter) or mouse input OR one event, i guess i could improve it making it take an event whitelist table /string and blacklist.