You have probably taken over this script from somewhere else, and the original version certainly used global variables, not local variables. "lasthigh" etc. are supposed to keep their values between runs. So you must define those variables either outside the run function, as in the original script, or define them as "static".

When you convert a script, first understand how it works. If the converted version then behaves wrongly, check the behavior of its variables with the debugging method described under "Tips & Tricks". This way you can find out fast which variable gets a different value than you expect.