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

Get the key pressed?

Started by Mackan90096, 27 March 2015 - 01:08 PM
Mackan90096 #1
Posted 27 March 2015 - 02:08 PM
Hi! I'm wondering if I can convert the p1 of this code to the character of the key, for example 30 to A (Found Here):

while true do
    e, p1, p2, p3, p4 = os.pullEvent()
    if(e == "modem_message") then
	  print(p4)
    elseif(e == "key") then
	  if(p1 == 28) then
		  send()
	  else
        
	  end
    end
  end


Thanks.

- Mackan
KingofGamesYami #2
Posted 27 March 2015 - 02:17 PM
Check out the "char" event. It's like the key event, except it returns the letter (a, b, c) and can deal with capital letters (A, B, C) which key events cannot.

Otherwise, you can use the keys table, ei

if p1 == keys.enter then
Mackan90096 #3
Posted 27 March 2015 - 03:11 PM
Ah, the char event works fine! Thanks

EDIT!

On a further range, it doesn't work, it does not detect the backspace nor the enter key.
Edited on 27 March 2015 - 02:33 PM
KingofGamesYami #4
Posted 27 March 2015 - 03:52 PM
Yeah, you'll have to use the key event for things without a single character. (shift, backspace, escape, etc.)

But, these are easy because the keys table has the values already stored.
MKlegoman357 #5
Posted 27 March 2015 - 03:53 PM
That's because the 'char' event is meant to be fired for any printable characters, not exactly keys of a keyboard. You should be using the 'char' event only for getting user input. To get if a key on a keyboard is pressed you should be using the 'key' event. Together with the keys table it is really easy to use:


local event, key = os.pullEvent("key")

if key == keys.a then
  ...
end
GopherAtl #6
Posted 27 March 2015 - 03:54 PM
not entirely clear what context you're doing this in, but more often than not, I just handle both "key" and "char" events, it's easier than trying to use only one and translate where you actually want the other.
Bomb Bloke #7
Posted 28 March 2015 - 12:04 AM
Eg,

while true do
    e, p1, p2, p3, p4 = os.pullEvent()
    if(e == "modem_message") then
          print(p4)
    elseif(e == "key") then
          if(p1 == keys.enter) then
                  send()
          elseif(p1 == keys.backspace) then
                  -- do backspace stuff
          end
    elseif(e == "char") then
          -- add character to string variable
    end
end

The idea is that when you press a character key, two events are fired - a key event, followed by a char event. In these cases, you ignore the key event and use the char event. When a non-character is pressed, you only get a key event.