Elisp: Loop
While Loop
Most basic loop in elisp is with while
.
(while test body)
, where body is one or more lisp expressions.
(let ((x 0)) (while (< x 4) (print (format "number is %d" x)) (setq x (1+ x))))
Example: While Loop Over a List
One common form to loop thru a list is using the while
function. In each iteration, pop
is used to reduce the list.
(let ((xx '(a b c))) (while xx (message "%s" (pop xx)))) ;; prints ;; a ;; b ;; c
Example: While Loop Over a Vector
;; iterate over a vector with while-loop (let (xx ii) (setq xx [0 1 2 3 4 5]) (setq ii 0) (while (< ii (length xx)) (insert (format "%d" (aref xx ii))) (setq ii (1+ ii)))) ; inserts 012345
Loop Fixed Number of Times
dotimes
-
(dotimes (VAR COUNT) BODY)
(dotimes (VAR COUNT RESULT) BODY)
- Loop a fixed number of times.
- Evaluate BODY with VAR bound to successive integers running from 0, inclusive, to COUNT, exclusive.
- Return nil or RESULT
- RESULT means, evaluate RESULT after loop to get the return value.
💡 TIP:
dotimes
is useful when you need to go ever a list and also get the current element's index.(dotimes (i 4) (insert (number-to-string i))) ;; inserts 0123, return nil
(let ((xx [3 4 5])) (dotimes (i (length xx)) (insert (number-to-string (elt xx i))))) ;; inserts 345
;; example. dotimes over a vector, with conditional exit (let ((xx [10 20 30 40 50])) (catch 'TAG743 (dotimes (i 99) (message "i %s %s" i (aref xx i)) (if (eq (aref xx i) 30) (throw 'TAG743 "got it") nil)))) ;; prints ;; i 0 10 ;; i 1 20 ;; i 2 30 ;; return ;; "got it"