key (event)
From ComputerCraft Wiki
Event key | |
Fired when any key (except Escape) is pressed while the terminal is focused. You can compare the values it gives you to the constants in the keys API (eg, keys.up, keys.down, etc). If the button pressed represented a printable character, then the "key" event will be followed immediately by a "char" event - you're generally better off pulling that if you're wanting text input (as "key" events don't indicate eg the case of what was typed, whereas "char" events do). When the button is released, a "key_up" event may be fired as well (assuming ComputerCraft 1.74 or later). | |
Returned Object 1 | The numerical key value of the key pressed |
Returned Object 2 | A boolean indicating whether the key event was generated while holding the key (true), rather than pressing it the first time (false). |
Example | |
Print each key pressed on the keyboard whenever a "key" event is fired. Use Ctrl+T (Windows) to terminate the loop. | |
Code |
while true do local event, key, isHeld = os.pullEvent("key") write( keys.getName( key ) ) print( isHeld and " is being held." or " was pressed." ) end |
Output | Any key that is pressed. |
Example | |
Moves a white square around the screen in response to the arrow keys. Press q to quit. | |
Code |
local x, y = 1, 1 local xSize, ySize = term.getSize() while true do -- Draw a white space at the current x/y co-ord: term.setBackgroundColor(colours.black) term.clear() term.setCursorPos(x, y) term.setBackgroundColor(colours.white) term.write(" ") -- Wait for a key event: local event, key = os.pullEvent("key") -- Act on it: if key == keys.up and y > 1 then y = y - 1 elseif key == keys.down and y < ySize then y = y + 1 elseif key == keys.left and x > 1 then x = x - 1 elseif key == keys.right and x < xSize then x = x + 1 elseif key == keys.q then break end end |
Key scan codes
These scan codes are also available as constants in the keys API, and can be translated from numerical codes to strings using keys.getName.