Function: dotimes

dotimes is a macro defined in subr.el.gz.

Signature

(dotimes (VAR COUNT [RESULT]) BODY...)

Documentation

Loop a certain number of times.

Evaluate BODY with VAR bound to successive integers running from 0, inclusive, to COUNT, exclusive.

Finally RESULT is evaluated to get the return value (nil if RESULT is omitted). Using RESULT is deprecated, and may result in compilation warnings about unused variables.

This macro has :around advice: cl--wrap-in-nil-block.

Probably introduced at or before Emacs version 21.1.

Source Code

;; Defined in /usr/src/emacs/lisp/subr.el.gz
(defmacro dotimes (spec &rest body)
  "Loop a certain number of times.
Evaluate BODY with VAR bound to successive integers running from 0,
inclusive, to COUNT, exclusive.

Finally RESULT is evaluated to get the return value (nil if
RESULT is omitted).  Using RESULT is deprecated, and may result
in compilation warnings about unused variables.

\(fn (VAR COUNT [RESULT]) BODY...)"
  (declare (indent 1) (debug dolist))
  ;; It would be cleaner to create an uninterned symbol,
  ;; but that uses a lot more space when many functions in many files
  ;; use dotimes.
  ;; FIXME: This cost disappears in byte-compiled lexical-binding files.
  (let ((temp '--dotimes-limit--)
	(start 0)
	(end (nth 1 spec)))
    ;; This test does not matter much because both semantics are acceptable,
    ;; but one is slightly faster with dynamic scoping and the other has
    ;; cleaner semantics.
    (if lexical-binding
        (let ((counter '--dotimes-counter--))
          `(let ((,temp ,end)
                 (,counter ,start))
             (while (< ,counter ,temp)
               (let ((,(car spec) ,counter))
                 ,@body)
               (setq ,counter (1+ ,counter)))
             ,@(if (cddr spec)
                   ;; FIXME: This let often leads to "unused var" warnings.
                   `((let ((,(car spec) ,counter)) ,@(cddr spec))))))
      `(let ((,temp ,end)
             (,(car spec) ,start))
         (while (< ,(car spec) ,temp)
           ,@body
           (setq ,(car spec) (1+ ,(car spec))))
         ,@(cdr (cdr spec))))))