Basically, on line 142, the while statement is apparantly accessing nil. If you run the program, he will behave properly at first, and when he goes to unload into the chest, the chest unloading bugs before items start going into the chest. The statement above it which does not put down the chest runs successfully if run independantly. What is going on? I was staring at it for a good 15-30 minutes with no idea what the hell is going on.

http://pastebin.com/iQzx6gy4

UPDATE: Nvm, I figured it out. I forget calling a local variable makes it local to that block, not local to that function. So I called x as local in the first if block, but else is treated as a separate block, where an x is not defined. >.>