AfraLISP - Learn AutoLISP for AutoCAD productivity

Program Looping

by Kenny Ramage

AutoLisp uses 2 kinds of loops, namely (repeat) and (while).
Let's have a look at the (repeat) function first :

(repeat)

The (repeat) function is a simple looping structure. It executes any number of statements a specific number of times. Like the (progn) function, all of it's expressions get evaluated, but they get evaluated once each loop.
Here's a simple example :

(defun c:loop ()
	(setq pt (getpoint "\nCentre of Rotation : "))
	(setq n  (getint "\nEnter Number of Steps : "))
 
	(repeat n
		(command "Rotate" "L" "" pt "20")
	)
   (princ)
)

Now draw a circle anywhere on the screen and then run the routine.
The circle should move around.
Note that the variable that controls the number of loops must be an integer.

(while)

The (while) function loops like (repeat) except that (while) has a conditional test. (while) will continue looping through a series of statements until the condition is nil. Here's an example :

(defun c:loop1 ()
	(while
		(setq pt (getpoint "\nChoose a point : "))
		(command "point" pt)
	)
  (princ)
)

In this example, you can continue to pick points until you press Enter.
(AutoLisp treats Enter as nil). When you press enter the loop will terminate.

Here's another example :

(defun c:loop2 () 
	(setq ptlist nil)
	(while
		(setq pt (getpoint "\nEnter Point or RETURN when done: "))
		(setq ptlist (append ptlist (list pt)))
	)
  (princ)
)

This example keeps on asking for a point and adding the point to a list of points, called ptlist. It uses the (append) function to merge the new point list to ptlist. As soon as you hit Enter the loop stops.
Run the routine, choose a few points and check the value of ptlist.
It should contain a long list of points.

The (while) function can also be used for programme iteration.
This means that a loop is continued until the results of one or more expressions, calculated within the loop, determine whether the loop is terminated. A common use of iteration is to increment a counter.
Have look at this example :

(defun c:loop3 ()
	(setq count 0)
	(while (< count 10)
		(princ count)
		(setq count (1+ count))
	)
  (princ)
)

You should get :

012345678910

If you know the number of times you want to loop, use (repeat), a much simpler command than (while).

Hint : Have you ever wondered how to make an AutoLisp routine Auto-Repeat?
Enclose the whole function or sub-function in a (while) loop.
This way, the function will keep on repeating until Enter or Cancel is hit.

Enough for now, my brain hurts…
In fact, I think I'm going "Loopy-Loo"
Cheers…