How can I correct this function compile error?

so the functions need to be outside the loop, so that they do not interfere with other aspects of the code.

Yes, they do, but that's not why.