Many decision branches are multi-forked—that is, there are several possible outcomes, each with a unique result. Rather than nest a series of (if) statements, a single (cond) function can handle a multi-fork branch extremely well.

Explanation: the (cond) function

(cond
                   (test1
expression11

                        expression1n
)

                (test2
expression21

                         expression2n
)

                              …
                (testn
expressionn1
)

                              …
                        expressionnn
(T nil)

) ;end cond

  • Each test expression is evaluated sequentially until one is found that is non-nil. It then evaluates those expressions that follow the test that succeeded, returning the value of the last of these expressions.
  • Any number of test expressions is possible.
  • It is common to use T as the final test expression as an error-checking mechanism in case all other tests fail. For example:

( T (prompt “\nNo conditions were met.”))

Example

(defun c:object ()
      (initget 1 “Circle Square Rectang”)
     (setq CMD (getkword “\nEnter object type Circle/Square/Rectangle: “))
     (setq PT (getpoint “\nEnter a point: “))
     (cond
         ((= CMD “Circle”) (command “circle” PT 0.5))
         ((= CMD “Square”) (command “pline” PT “@1<0” “@1<90” “@1<180” “c”))
         ((= CMD “Rectang”) (command “pline” PT “@2<0” “@1<90” “@2<180” “c”))
     )
)

  • A copy of this example is on your class disk as OBJECT.LSP

PRACTICE

Create an AutoLISP routine that will let the user select from a list of blocks and insert it. Test it in the file OFFICE.dwg. Estimated time for completion: 10 minutes.

Steps to solution

1. Ask user to select from a list of blocks.
2. Test which block name was chosen and insert the block.

Solution

(defun c:furn ()
(initget 1 “Chair Desk PC Plant”)
(setq FURN (getkword “\n Enter furniture type to insert Chair/Desk/PC/Plant: “))
(cond
((= FURN “Chair”) (command “insert” “Chair” “s” “1” pause pause))
((= FURN “Desk”) (command “insert” “Desk” “s” “1” pause pause))
((= FURN “PC”) (command “insert” “PC” “s” “1” pause pause))
((= FURN “Plant”) (command “insert” “Plant” “s” pause pause))
)
(princ)
)

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