The question is not how to figure out when to exit the lua script, the question is how to exit the lua script, and that can sometimes be tricky or complicated as return "exit" only works from hangup hook.
Are you positive that it works only from a hangup hook? It seems to work at the end of any loop: