Search code examples
while-loopcommon-lispinfinite-loop

Does Common Lisp have any syntactic sugar for a while True, i.e. infinite, loop?


Common Lisp's LOOP macro has made it notorious for having everything and the kitchen sink when it comes to looping. Despite this, while loops are a bit difficult. Is the special case of while true, i.e. infinite loops, an exception? That is, does Common Lisp offer any syntactic sugar for infinite loops?

My attempts to find anything like this online have failed. This cookbook suggests making a circular list and then telling the LOOP macro to do something for each element in that infinite list. This clearly works, but it's not any sort of syntactic sugar. For comparison, the R language lets users write while(TRUE){...} as repeat{...}. This is the sort of syntactic sugar that I have in mind.

Note: As much as I love seeing Lisp macros, I'm not asking for anyone to implement repeat in Common Lisp. I want to know what is already in the language from the get go.


Solution

  • The simple LOOP macro is an infinite loop.

    (loop
      (print 1)
      (print 2))
    

    There's an implicit block named NIL around the body, so you can exit the loop using (return). This is the equivalent of break in other languages, although you can also supply a value to be used as the value of the loop expression.