From e9f0bc17a6f57249317c08c11dfc910656f4faac Mon Sep 17 00:00:00 2001 From: Patrick Schwarzer Date: Thu, 1 May 2025 03:52:12 +0200 Subject: [PATCH] Implement KeyPressed --- engine/input.cpp | 30 ++++++++++++++++++++++++++---- test.lua | 4 ++-- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/engine/input.cpp b/engine/input.cpp index 502f512..9f6efbe 100644 --- a/engine/input.cpp +++ b/engine/input.cpp @@ -1,6 +1,7 @@ #include +#include extern "C" { #include @@ -11,35 +12,56 @@ extern "C" { #include "input.h" -// Implement KeyPressed that basically just gets called once on process_input down = true -// resets when the key is released again +static std::unordered_set heldKeys; void process_input(SDL_Keysym &keysym, bool down, lua_State *luaState) { lua_getglobal(luaState, "engine"); if (lua_istable(luaState, -1)) { + int scancode = keysym.scancode; + if (down) { lua_getfield(luaState, -1, "KeyDown"); if (lua_isfunction(luaState, -1)) { - lua_pushinteger(luaState, keysym.scancode); + lua_pushinteger(luaState, scancode); if (lua_pcall(luaState, 1, 0, 0) != LUA_OK) { const char* error = lua_tostring(luaState, -1); std::cerr << "Lua error in engine.KeyDown: " << error << std::endl; } } + + if (heldKeys.find(scancode) == heldKeys.end()){ + heldKeys.insert(scancode); + + lua_pop(luaState, 1); + + lua_getfield(luaState, -1, "KeyPressed"); + if (lua_isfunction(luaState, -1)) { + lua_pushinteger(luaState, scancode); + + if (lua_pcall(luaState, 1, 0, 0) != LUA_OK) { + const char* error = lua_tostring(luaState, -1); + std::cerr << "Lua error in engine.KeyPressed: " << error << std::endl; + } + } + } } else { lua_getfield(luaState, -1, "KeyReleased"); if (lua_isfunction(luaState, -1)) { - lua_pushinteger(luaState, keysym.scancode); + lua_pushinteger(luaState, scancode); if (lua_pcall(luaState, 1, 0, 0) != LUA_OK) { const char* error = lua_tostring(luaState, -1); std::cerr << "Lua error in engine.KeyReleased: " << error << std::endl; } } + + heldKeys.erase(scancode); } } + + lua_pop(luaState, 1); } diff --git a/test.lua b/test.lua index c4255c3..4c617be 100644 --- a/test.lua +++ b/test.lua @@ -3,6 +3,6 @@ function engine.KeyReleased(key) print("Released key: " .. key) end -function engine.KeyDown(key) - print("Key down: " .. key) +function engine.KeyPressed(key) + print("Pressed key: " .. key) end \ No newline at end of file