input help

i want to bind a menu to the f6 key this is what i have it sorta works it comes out weird and most of the time the button has to be help which i don’t want. I want to press f6 once the menu comes out and then press f6 again to close the menu.



local function OpenPanel()
	if !IsValid(df) then
		timePanel()
	end

	df:MoveTo(0 * _wMod, 0 * _hMod, 1, 0, 1)
end

local function ClosePanel()
	if !IsValid(df) then return end

	df:MoveTo(-200 * _wMod, 0 * _hMod, 1, 0, 1)
end

hook.Add("Think", "Menu", function()
	local p = false
	if input.IsKeyDown(KEY_F6) then
		p = !p
	end

	if (p) then
		OpenPanel()
	else
		ClosePanel()
	end
end)


As you have the code, you set p to false each time Think runs which means p will always be true while f6 is held-down and false when it is released. While it makes an ok method to duplicate the TAB / scoreboard / +showscores key, it keeps re-executing the logic when it should only execute once on press and once on release with logic in the panel ( which will receive key-presses if it has focus or accepts input ) to handle the button: https://dl.dropboxusercontent.com/u/26074909/tutoring/vgui/open_menu_key_tap_open_and_key_hold_release_close.lua.html – this is one method which uses pre-existing hooks and passes control to the panel when it is open ( while it knows the state of the button when it is created so it knows how to handle key-taps vs key being held )… This is a lengthy way of doing it but it is one of the safest to ensure the logic is handled for panels that accept input…

Don’t use Think to identify a button without a controlled toggle. Otherwise you’ll spam the open-menu function if it isn’t missed… I’d recommend using PlayerBindPress ( which means that F6 must be bound to a key on the client for it to work, but it is reliable; alternatively you can use the other key-press hooks but they’re not reliable when users hold keys down which leaves think but you’re missing a controlled toggle to track the state of the button and ensure it only executes the command once per press )…

A controlled toggle is my terminology which means you need some variable which sets itself to true on press and false on release with it in the if statement logic… ie … if key-down && !pressed then … else if !key-down and pressed then … end

https://dl.dropboxusercontent.com/u/26074909/tutoring/logic/controlled_toggles.lua.html

That’ll ensure the code is executed exactly once per press… You need another variable to track the panel state ( or a reference to the panel to see if it is valid / visible / etc… ) so you know which function to call…

If you want to use Think then add the controlled toggle to ensure it opens once. Remove the p value unless you want to require the key be held ( but with a controlled toggle you can define what happens on tap / hold / release so p is essentially useless )…