Page 1 of 1

[Feature Request] Keyboard Function - KeyReleased() function

Posted: Fri Apr 17, 2009 8:00 pm
by zer0
Is it possible to make a KeyReleased() function that detects if a key has been just released?

Reason I ask is that I am making a recording in-game coordinate system, and it needs to save the coordinate when the movement keys have been released.

One way I did do it is by waiting until the keyPressed returns false.

Code: Select all

function keyPressedOnce(key)
	if (keyPressed(key)) then
		while (keyPressed(key)) do
			coroutine.yield()
		end
		return true
	end
	return false
end
However I run into big problems when multiple keys are pressed, as it enters the while loop until the user releases the first detected key. Which is kinda pointless, because when moving your usually pressing forward and the left or right at the same time.

Any ideas?

Re: [Feature Request] Keyboard Function - KeyReleased() function

Posted: Fri Apr 17, 2009 8:21 pm
by zer0
I think I know of a way I can do it, simply have a boolean variable for each key for example:

Code: Select all

while(true) do
  if (keyboardPress(key.VK_W)) then
    move_forward = true
  else
    if (move_forward == true) then
      -- save coordinate
      move_forward = false
    end
  end
end
make sense?

Re: [Feature Request] Keyboard Function - KeyReleased() function

Posted: Fri Apr 17, 2009 11:29 pm
by Administrator
Or, even easier: Keep an array of previous key states. Just iterate through each update and check for changes.

Code: Select all

-- Init
keystate = {};

Code: Select all

-- Update, must be called at least once right after init
-- Should also be called at the *end* of every update cycle
for i,v in pairs(key) do
  keystate[i] = keyPressed(v);
end
Now you can detect key presses or releases easier.

Code: Select all

function keyJustPressed(k)
  if( keyPressed(k) and not keystate[k] ) then
    return true;
  end

  return false;
end

function keyJustReleased(k)
  if( not keyPressed(k) and keystate[k] ) then
    return true;
  end

  return false;
end