Jorge
Jorge

Reputation: 75

Initialize counter variable in Common Lisp

I want to use a variable inside a Common Lisp function as a counter, started from a desired number and used inside a loop while.

(defun x(c)
   (setq i 4)
   (loop while condition do 
        ;do something
        (incf i)))

the instructions setq and incf are not appropiate for this. What is the standard way to manage a counter variable in clisp?

Upvotes: 0

Views: 602

Answers (2)

Rainer Joswig
Rainer Joswig

Reputation: 139251

In Common Lisp you need to define your variables. Your variable i is undefined. That's a mistake.

(defun x (c)
   (setq i 4)                 ; undefined variable i
   (loop while condition do 
        ;do something
        (incf i)))            ; undefined variable i

Define your variable:

CL-USER 9 > (defun x (c)
              (let ((i 4))     ; defining/binding local variable i
                (loop while (< i 10) do
                      (print i)
                      (incf i))))
X

CL-USER 10 > (x :foobar)

4 
5 
6 
7 
8 
9 
NIL

But as the other answer by coredump shows, loop provides its own way to define a variable and iterate over it.

Upvotes: 7

coredump
coredump

Reputation: 38799

LOOP is explained in details in §22. LOOP for Black Belts.

(defun x (c)
  (loop 
    for i from 4 
    while <condition> 
    do <something>))

Upvotes: 8

Related Questions