Raw key events

From ComputerCraft Wiki
Revision as of 23:54, 4 October 2012 by 67.189.72.22 (Talk)

Jump to: navigation, search

The built-in os has a function to read incoming keystrokes. But it also implements the functions to move the cursor while typing. This is not always a desired feature; imagine a case in which you want to make a menu with a controllable cursor around the menu entries. The current read() function won't let you.

Detecting keystrokes

In case I made you think the OS sucks, it doesn't (all the time). Because this OS is not Windows, we can access lower-level functions, such as os.pullEvent(). And that's the one that we're going to use:

function rawread()
    bRead = true
    while(bRead) do
        local sEvent, param = os.pullEvent("key")
        if(sEvent == "key") then
            break
        end
    end
end

This function waits for any key, then exits.

Figuring out the key

We can detect any key, but not which key. To find it out, we have to add some further logic to the code:

function rawread()
    while true do
        local sEvent, param = os.pullEvent("key")
        if sEvent == "key" then
            if param == 28 then
                print("Enter detected")
                break
            end
        end
    end
end

This function waits for the Enter key to be pressed. If so, it writes "Enter detected" to the screen and exits.

However, this is only good for checking single keys. Also, what if you don't really want to look up the scan code on this page every time you code? Fortunately there is a solution: the keymapper API. See page for details.

Key scan codes

The scan codes are typical DirectX numbers.

Key Code
Escape 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
0 11
Minus 12
Equals 13
Backspace 14
Tab 15
Q 16
W 17
E 18
R 19
T 20
Y 21
U 22
I 23
O 24
P 25
Key Code
Left Bracket 26
Right Bracket 27
Enter 28
Left Control 29
A 30
S 31
D 32
F 33
G 34
H 35
J 36
K 37
L 38
Semicolon 39
Apostrophe 40
Tilde (~) 41
Left Shift 42
Back Slash 43
Z 44
X 45
C 46
V 47
Key Code
B 48
N 49
M 50
Comma 51
Period 52
Forward Slash 53
Right Shift 54
Numpad * 55
Left Alt 56
Spacebar 57
Caps Lock 58
F1 59
F2 60
F3 61
F4 62
F5 63
F6 64
F7 65
F8 66
F9 67
F10 68
Key Code
Num Lock 69
Scroll Lock 70
Numpad 7 71
Numpad 8 72
Numpad 9 73
Numpad - 74
Numpad 4 75
Numpad 5 76
Numpad 6 77
Numpad + 78
Numpad 1 79
Numpad 2 80
Numpad 3 81
Numpad 0 82
Numpad . 83
F11 87
F12 88
Numpad Enter 156
Right Control 157
Numpad / 181
Right Alt 184
Key Code
Home 199
Up Arrow 200
Page Up 201
Left Arrow 203
Right Arrow 205
End 207
Down Arrow 208
Page Down 209
Insert 210
Delete 211

Source: Nexus Wiki