Limiting Acceptable String Input Values with autolisp in AutoCAD

In addition to the bit option that restricts input, there is a keyword option of (initget) that expands the acceptable responses to include specific keyword strings. String input can be limited to selected responses by using keywords along with the (getkword) function.

Explanation: (initget) with keyword

(initget [bit] [keyword])

The keyword string is a single string that contains all acceptable keywords separated by spaces.

(initget 1 “Red White Blue”)

  • By capitalizing the minimum input required for each keyword, the user only needs to enter the capital letter to have the whole keyword returned.
  • Keywords work with all (getxxx) functions except (getstring).
  • The bit option can still be included if you want the user to input either a keyword or a number.

(initget 1 “Pi Two-pi”)
(setq X (getreal “Enter a number or [Pi/Two-pi]: “)

Explanation: the (getkword) function

To use (initget) with a group of keywords you have to ask for the keywork through another string function, (getkword). This function limits acceptable string responses to those in the keyword.

(getkword [prompt])

  • To be functional, (getkword) requires a prior (initget) expression that includes acceptable keywords.
  • The function returns a string, the full keyword chosen even if only the capitalized letter is typed in.

Example

Command: (initget “LAyer LInetype”)
nil
Command: (setq ANS (getkword “Enter LAyer or LInetype: ”))
Enter LAyer or LInetype: D

Invalid option keyword.
Enter LAyer or LInetype: L
Ambiguous response, please clarify…
LAyer or LInetype? LA
“LAyer”
Command:

PRACTICE

See also  AutoCAD and AutoLISP are Two Separate Programs

Modify BOX1.LSP to allow the user to draw a red, yellow, or blue box. You will need to adjust and control the AutoCAD variable CECOLOR.

(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)
(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”)
(redraw)
(setvar “cmdecho” CE-SAV)
(setvar “cecolor” CC-SAV)
(princ)
)

  • A complete solution to this exercise is on your class disk as BOX1-F.LSP
Back to top button