I suspect it has something to do with the fact that you're not managing the events properly. Specifically, you make one call to os.pullEvent at the very beginning of the main loop, assigning a value to each of two variables. You then have your 'energy' function (odd placement, but that shouldn't...