Elegant breaking from nested loops

I have to chime in and agree that adding such a mechanism would be nice. Perhaps a more generic one, though. In Common Lisp you have named blocks, which can appear pretty much anywhere:

;; Prints up to 16 numbers.  If N is >= 16, it will return 69,
;; otherwise it will return 42.
(defun foo (n)
  (block my-block
    (dotimes (i n)
      (print i)
      (when (= i 16)
        (return-from my-block 69)))
    42))

I would, however, rather see a true goto added to Crystal. Maybe something more similar to Common Lisp’s TAGBODY where the labels are scoped and behavior is very well defined. A goto would really make writing CPU emulators, and porting certain pieces of code, a heck of a lot easier and cleaner.

1 Like

We should’t abuse goto if added it. anyway, maybe it only can be used in some special block.

BTW, Ruby use catch block with throw keyword for this.

        catch :miss_data do
          # deep loop ....                          
          throw :miss_data, return_value
          ....                          
        end                             
1 Like

Managed Doom … very cool! :japanese_ogre:

1 Like