最简单的形式
(while TRUE-OR-FALSE-TEST
BODY...)
比如:
(setq x 10
total 0)
(while (plusp x) ; while x is positive
(incf total x) ; add x to total
(decf x)) ; subtract 1 from x
初始设置x=10,total=0
如果x>=0则继续,否则退出循环
每次循环都将当前的x的值加到total上,然后让x=x-1
执行了10次循环后,最后x的值为-1.
下面的这个例子的代码演示了如何遍历list中的每个元素,并打印:
(setq animals '(gazelle giraffe lion tiger))
(defun print-elements-of-list (list)
"Print each element of LIST on a line of its own."
(while list
(print (car list))
(setq list (cdr list))))
(print-elements-of-list animals)
car函数返回list中的第一个元素
cdr函数将list中第二个元素开始的元素作为一个新的list返回
break中断循环
如果我们要实现常见的break跳出循环,比如像下面的JavaScript代码:
var x = total = 0;
while (true) {
total += x;
if (x++ > 10) {
break;
}
}
ELisp中应该这样写:
(setq x 0 total 0)
(catch 'break
(while t
(incf total x)
(if (> (incf x) 10)
(throw 'break total))))
catch函数获取到里面throw函数返回的total,当然也可不必返回有效值,用nil即可。
(throw 'break nil)
continue跳过后面代码,进入下一个循环
或用catch ‘break,还可以实现continue
(setq x 0 total 0)
(while (< x 100)
(catch 'continue
(incf x)
(if (zerop (% x 5))
(throw 'continue nil))
(incf total x)))