Tuesday, January 4, 2011

getkword initget and default in AutoCAD’s AutoLISP

Looking in AutoCAD’s AutoLISP Reference there are examples like this:

(initget "Abc Def _Ghi Jkl")
(getkword "\nEnter an option (Abc/Def): ")

(initget 1 "Yes No")
(setq x (getkword "Are you sure? (Yes or No) "))

First off both examples should be updated to follow how command prompts are looking in AutoCAD like in the COPY command:

Specify base point or [Displacement/mOde] <Displacement>:

That means the examples would look like this when using:

(getkword "\nEnter an option [Abc/Def]: ")

(setq x (getkword "Are you sure? [Yes/No]: "))

Now to default. How is it achieved? Default should happen when you press Enter and thus initget 1 cannot be used because bit 0 set to 1 “Prevents the user from responding to the request by entering only ENTER”.

The documentation says on the return values of getkword: “A string representing the keyword entered by the user; otherwise nil, if the user presses ENTER without typing a keyword. The function also returns nil if it was not preceded by a call to initget to establish one or more keywords.”

The trick is then to check for if getkword is nil using (not kw).

So finally here is a sample solution of how get default:

(initget "Yes No")
(setq kw (getkword "Are you sure? [Yes/No] <Yes>: "))
(cond 
  ((or (not kw) (= "Yes" kw)) (alert "YES")) 
  ((= "No" kw) (alert "NO")) 
)

And here is the result and as you can see Yes is the default:

This can also be used with other get*** functions like getdist, getint, getorient, getpoint, getreal and getstring

2 comments:

  1. Instead of "cond" I would prefer to use shorter "if":
    (if (= "No" kw) (alert "NO")(alert "YES"))

    Nikolay N.Poleshchuk,
    http://poleshchuk.spb.ru/cad/eng.html

    ReplyDelete
  2. I agree, when there are only two choices "if" is a good choice. But with "cond" it is easier to extend with multiple choices.

    ReplyDelete