Lesson22b – Processing the Elements of a List.

When we are working with a list of data, we frequently need to work with each individual element rather than the list as a whole. For instance, if we wanted to create a point, PT2, which is twice as far from the origin as PT1, then we will want to increase each of its coordinates separately by a factor of 2. By use of the (foreach) function, we are able to act on each element in a list.

Explanation: the (foreach) function

(foreach item list
… expression …

)

The (foreach) function temporarily holds each element in list in a local variable item. The expression within the (foreach) will then perform appropriate calculations using the constantly changing item symbol.

Example

Command: (setq PTLST ‘((2.0 2.0 0.0) (2.0 3.0 0.0) (1.0 2.0 0.0))) ((2.0 2.0 0.0) (2.0 3.0 0.0) (1.0 2.0 0.0))
Command: (foreach PT PTLST (command “circle” PT 1.0))

PRACTICE

Modify the BOX1.LSP file to draw a 1⁄2” circle at each of the corners of each of the boxes. Estimated time for completion: 5 minutes.

Solution

(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”)
  (foreach PT (list PT1 PT2 PT3 PT4)
        (command “circle” PT 0.25)
  );end foreach
);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-H.LSP.

Object Snaps vs. Keyboard Entry
When you are running AutoLISP routines that place points you will need to make sure you have the Keyboard Entry overriding the Object Snaps. You should either set OSNAPCOORD to 1 in your routine or change the option “Priority for Coordinate Data Entry” to “Keyboard Entry” in the Options dialog> User Preferences tab.

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons
SUBSCRIBE TO OUR NEWSLETTER

It's FREE!

Sign up and receive an email every time a new tutorial is published