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

Trouble with events

Started by modkip, 02 August 2017 - 07:12 AM
modkip #1
Posted 02 August 2017 - 09:12 AM
Hi all

Im having some trouble with a script
There's a pice in it that gives the user a [Y/N] prompt,
but after the prompt it still types the character that's chosen.

[indent=1]local event,key = os.pullEvent("key")[/indent]

[indent=1]if key == 21 then[/indent]
[indent=1]somescript()[/indent]
[indent=1]elseif key == 49 then[/indent]
[indent=1]– some code –
end[/indent]

[indent=1]Function somescript()[/indent]

[indent=1]write("id: ")[/indent]
[indent=1]id = read() – This is where the character shows up[/indent]

[indent=1]– some more code –[/indent]


Is there some way to prevent the char-event from firing, or to prevent the character showing up when i use read?

Thanks in advance!
KingofGamesYami #2
Posted 02 August 2017 - 12:12 PM
Sure, pull the char event instead of the key event. Then it'll be out of the queue when read starts.
Codinget #3
Posted 02 August 2017 - 12:14 PM
Hi

The reason read() gets the char is indeed the char event, so you should consume it before calling read()
You should probably also consume the key_up event

The code now looks like so:


local event, key=os.pullEvent("key")
function somescript()
  local a,b=os.pullEvent("char")
  a,b=os.pullEvent("key_up")
  write("id: ")
  id=read()
end
if key==21 then
  somescript()
elseif key==49 then
  --some code
end

What I did was just add two os.pullEvent() to get rid of the char event and the key_up.

–apparently, I was too slow
modkip #4
Posted 02 August 2017 - 12:39 PM
Thanks guys, using a char event instead of a key event solved the issue, and its working great now!
Wojbie #5
Posted 02 August 2017 - 12:52 PM
But I believe that there are keys that don't generate char event. Like esc.
EDIT: Make that ctrl. Forgot exit exits gui.
Edited on 02 August 2017 - 12:52 PM
Bomb Bloke #6
Posted 02 August 2017 - 02:24 PM
Esc doesn't generate a key event, either, but if you're only interested in y / n, then buttons such as down / shift / Ctrl / etc (which do generate key events without following char events) are of no concern.

Personally I'd go with something along the lines of Codinget's method, as this allows you to easily detect y / n regardless as to whether caps lock is on or not.