Love2d: Functions to check if key was pressed\released

Love2d only provides you with a function to check if specific key is currently down, love.keyboard.isDown(key), and no functions to check if key was pressed\released.
But there are events, which can be used to implement such functions.
Code below demonstrates sample implementation.

love.keyboard.keysPressed = { }
love.keyboard.keysReleased = { }
-- returns if specified key was pressed since the last update
function love.keyboard.wasPressed(key)
	if (love.keyboard.keysPressed[key]) then
		return true
	else
		return false
	end
end
-- returns if specified key was released since last update
function love.keyboard.wasReleased(key)
	if (love.keyboard.keysReleased[key]) then
		return true
	else
		return false
	end
end
-- concatenate this to existing love.keypressed callback, if any
function love.keypressed(key, unicode)
	love.keyboard.keysPressed[key] = true
end
-- concatenate this to existing love.keyreleased callback, if any
function love.keyreleased(key)
	love.keyboard.keysReleased[key] = true
end
-- call in end of each love.update to reset lists of pressed\released keys
function love.keyboard.updateKeys()
	love.keyboard.keysPressed = { }
	love.keyboard.keysReleased = { }
end
And then you can use it as simple as:
if (love.keyboard.wasPressed('r')) then
	-- restart level
end

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.