Proper key press proggraming
Hey everyone i just wanted to share a simple way of setting multiple functions related to the same hook; using clean and maintanable code.
example problem: i have a gamemode with multiple menus, one when i press C and another one when i press P.
the first thought that comes to mind is using the function:
function GM:PlayerButtonDown(pl, button )
if(button == 13) then
--some code or maybe a function that encapsulates that code
end
return true
end
this code sucks because the more menus i add the bigger the function gets and also it gets harder to organize.
what you could do instead is create a function named after the keypress, in this case, we would create an object named keyPress and then:
keyPress = {}
keyPress[13] = function(pl, button)
print(pl:GetEyeTrace().Entity())
end
function GM:PlayerButtonDown(pl, button )
if(keyPress[button] ~= nil) then
keyPress[button](pl,button)
end
return true
end
now if i want to add the P menu, all i would have to do is create a function and assign it to keyPress[26].
anyway, sorry if my example didnt quite show how useful it is, but trust me, whenever you have a situation with multiple ifs try finding a way to run that code without the if, it will make your code much much better.
Nice! But be sure to localise that keyPress table <3