Reputation: 75
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
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
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