# The Simplest Looping Function (repeat) with autolisp in AutoCAD

Programs frequently need to perform the same series of expressions multiple times. Rather than copy the same line a given number of times, the (repeat) function simplifies the process.

Explanation: the (repeat) function

(repeat number
… expression
)

The number is the number of times, in integers, to repeat the enclosed expressions.

Provided you can predetermine the number of loops desired, the (repeat) function is the simplest choice.

Example

(defun c:MCIRCLE ()
(setq NUMBER (getint “\nEnter number of circles: “))
(setq CENTER (getpoint “\nSelect center point: “))
(setq RADIUS (getdist CENTER “\nRadius of 1st circle: “))
(setq INCREMENT (getdist “\nEnter radius increment: “))
(repeat NUMBER
(command “circle” CENTER RADIUS)
;_ end of repeat
(princ)

) ;_ end of defun

• A complete solution to this exercise is on your class disk as MCIRCLE-A.LSP.

Note: With the (repeat) function and the other branching and looping functions, it is a good programming technique to indent all the arguments to the looping or branching function for easier readability. Visual LISP will do this for you automatically as you type or when you use the Format buttons.

PRACTICE

Modify the BOX1.LSP routine to include a prompt for the number of boxes to be drawn.

Solution

See also  How to interpret and manipulate an entity definition list (association list) with autolisp in AutoCAD

(defun c:BOX1 ()
(graphscr)
(setq CE-SAV (getvar “cmdecho”))
(setvar “cmdecho” 0)
(setq CC-SAV (getvar “cecolor”))
(initget 1 “Red Yellow Blue”)
(setq CLR (getkword “\nSelect Red/Yellow/Blue: “)) (setvar “cecolor” CLR)
(initget 1)
(repeat (getint “\nEnter number of boxes: “)
(initget 1)
(setq PT1 (getpoint “\nFirst corner of box: ”))
(initget 1)
(setq PT2 (getcorner PT1 “\nOpposite corner: ”))
(setq X1 (car PT1))
(setq X2 (car PT2))
(setq Y1 (cadr PT1))
(setq Y2 (cadr PT2))
(setq PT3 (list X1 Y2))
(setq PT4 (list X2 Y1))
(command “pline” PT1 PT3 PT2 PT4 “close”)
);end repeat
(redraw)
(setvar “cmdecho” CE-SAV)
(setvar “cecolor” CC-SAV)
(princ)
)

• A complete solution to this exercise is on your class disk as BOX1-G.LSP.