Hello Iain.
Quick practical answer:
You'd have to launch your loop as a sub event of the "Key press" event.
Now for a bit more explanation:
It highly depends on the context and what you are trying to achieve.
I'd suggest you to have a look at how events work if you're still (understandably) struggling with this concept.
You can also check more about the loops in C2 as they are part of the system references.
As I said earlier, it depends a lot on the context of what you are trying to do. If you could explain a bit more what is the purpose of your loop and even provide a Capx, it would help us help you ^^
I hope the few manual articles already enlightened a bit your way though.
As for functions. Tricky question again ^^
There is no built-in way to reproduce functions as you know them in coding language.
Nevertheless you can use groups act on their activeness and use Global variable as parameters.
Another solution, closer to what you are used to, is to use the custom plugin function.
Here, I hope this provides some answers already.