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

Event refusing to queue?

Started by EveryOS, 08 April 2016 - 10:59 PM
EveryOS #1
Posted 09 April 2016 - 12:59 AM
I have some code:

local c, x, y
local function tobinary(code)
  --From Online
  local rest, i
  local t ={}
  while code > 0 do
    rest = math.fmod(code, 2)
    table.insert(t, rest)
    code = (code - rest)/2
  end
  local x = table.concat(t)
  if string.len(x) <= 8 then
    for i = 0, 7 - string.len(x) do
	  x = '0'..x
    end
  else
    x=string.sub(x, #x - 8, #x)
  end
  return x
end
function getKeyboardInput()
  coroutine.yield()
  os.queueEvent('key')
  local tEveArgs = {coroutine.yield('key')}
  if tEveArgs[2] == 219 then
    printError('Windows 8 key not supported')
    tEveArgs[2] = 0
  end
  --print(type(tEveArgs[2]))
  if tEveArgs[2] == nil then
    tEveArgs[2] = 0
  end
  return tobinary(tEveArgs[2])
end
function getMouseInput()
  --This is very accurate, assuming the mouse stays in canvas.
  os.queueEvent('')
  local events = {coroutine.yield()}
  local noBin = '00000000'
  if c == nil or events[1] == 'mouse_up' then
    c = noBin
    x = noBin
    y = noBin
  elseif events[1] == 'mouse_click' or events[1] == 'mouse_drag' then
    if events[2] == 1 then
	  c = '00000001'
    else
	  c = '00000010'
    end
    x = tobinary(events[3])
    y = tobinary(events[4])
  end
  return c, x, y
end
while true do
  print(getKeyboardInput())
  for k,v in ipairs({getMouseInput()}) do
    print(v)
  end
end
Even though I queued my event, it still yields until I press a key.

Why?
Lyqyd #2
Posted 09 April 2016 - 01:09 AM
What will the first three lines of your getKeyboardInput function do?
EveryOS #3
Posted 09 April 2016 - 01:17 AM
In the bios of CC, os.pullEventRaw = coroutine.yield

So first I make sure there are no previously queued event.
The first one removes the events from the mouse if any are found


Then I queue the needed event
Then I pullEvent

I was just using coroutine.yield because that's less likely to be overwritten than pullEventRaw
Edited on 08 April 2016 - 11:18 PM
Bomb Bloke #4
Posted 09 April 2016 - 01:45 AM
The first one removes the events from the mouse if any are found

And what does coroutine.yield() do if no events are in the queue? It yields until there is one.

If you really want to ensure no key events are already in the queue (and you probably don't), you'd queue some random event type (I like to use tostring({})) and then pull that. All events found in the queue prior to that one would be discarded.
EveryOS #5
Posted 09 April 2016 - 02:21 AM
Ok… That fixes the yielding, but in exchange for actually being able to press a button.
Lyqyd #6
Posted 09 April 2016 - 02:27 AM
All you needed to do was to remove the initial yield.