Hello. I am trying to write a game engine with Lua+Allegro. I've got a lot of it done, with the exception of keyboard input. I am clueless as to how to get the keyboard presses in Allegro and C into a Lua script, so that the Lua script can just call something like
isKeyDown(KEY_ESC)
(obviously, isKeyDown would be a C function that lua can call).
Could someone help me with this?
I think what you want is a callback for Lua.
ie:
OnKeyDown(int key)
That you implement in Lua. But I don't know Lua, so I'm just throwing stuff out there.
Read the manual and Programming In Lua. Especially the parts on registering C functions for Lua.
What I was thinking of is more of a function that returns a boolean and accepts the key to check, like the key[] array in Allegro does, only from within Lua. I'd like to avoid callbacks, and I don't know how to do callbacks in Lua.
edit:
I have read the manual, and can register functions and call them from Lua. That works. What I want to know is how to get the constants KEY_* into Lua so that when I call a isKeyDown or similar function it can accept these and return the boolean.
The same way you would register any other global value.
So, if I understand this correctly, I should set the KEY_* variables after initializing the Lua VM, as such:
lua_pushinteger(lvm,KEY_A); lua_setglobal(lvm,"KEY_A"); lua_pushinteger(lvm,KEY_B); lua_setglobal(lvm,"KEY_B"); lua_pushinteger(lvm,KEY_B); lua_setglobal(lvm,"KEY_B"); //And so on
Then define and register the isKeyDown function:
That part is fairly straightforward, thank you X-G. However, the setting of global KEY_* variables in the Lua VM is very tedious. Is there an elegant way of doing that?
I imagine you could loop through them all with some fancy for loop.
I found the defines in allegro/keyboard.h:
#define KEY_A __allegro_KEY_A #define KEY_B __allegro_KEY_B #define KEY_C __allegro_KEY_C #define KEY_D __allegro_KEY_D #define KEY_E __allegro_KEY_E
I wrote the following program to take this text and turn it into the lines of code I need:
1 | #include <stdio.h> |
2 | |
3 | int main() |
4 | { |
5 | char buffer[100]; |
6 | |
7 | int i; |
8 | |
9 | for(i=0;i<127;i++) { //127 different keys, see allegro/keyboard comments |
10 | scanf("%s",buffer); |
11 | scanf("%s",buffer); |
12 | printf("lua_pushinteger(lvm,%s);\nlua_setglobal(lvm,\"%s\");\n",buffer,buffer); |
13 | scanf("%s",buffer); |
14 | } |
15 | return 0; |
16 | } |
Which, when I copy+paste the lines from the include file into stdin and redirect stdout to a file, gives me a file with the code neatly written for me.