Iterating through a table of keyboard keys
Posted: Wed May 26, 2021 1:57 pm
When I started with LÖVE, I used to have an ugly bunch of keyboard callback checks, like these in the code below:
Later, I got rid of them by creating a table with keyboard keys for keys and state variables for values. Iterating through such a table and checking the direction variables looked nice and took less space.
Is it a good practice to handle callbacks like this? I thought that the table could take some extra memory, especially when you have to check plenty of keys.
Code: Select all
function love.keypressed(key)
if key == 'd' then
player.right = true
end
if key == 'a' then
player.left = true
end
end
function love.keyreleased(key)
if key == 'd' then
player.right = false
end
if key == 'a' then
player.left = false
end
end
Code: Select all
keys = {
'a': 'left',
'd': 'right'
}
--...
function love.keypressed(key)
for k, d in pairs(keys) do
if key == k then
player[d] = true
end
end
end
--the same with keyreleased