The variables `key`, `mapbackward`, `mapforward` are global. There are two possible ways to fix. Make them script local or put the codes into a function.