4

I want to ask a second question to the user depending on the answer to the first one.

(defun something (a b)
  (interactive
   (list
    (read-number "First num: ")
    (read-number "Second num: ")))
  (message "a is %s and b is %s" a b))

So I need a way to test the entry values :

(defun something-else (a &optional b)
  (interactive
   (list
    (read-number "First num: ")
    (if (< a 2)
        (read-number "Second num: "))))
  (message "a is %s" a))

But

if: Symbol's value as variable is void: a

Question : How can I use interactive in a really interactive way?

2 Answers 2

6

Interpret the form in interactive as kind of subprogram which delivers the list of argument values as return value. You can have local variables there with the help of a let-like form.

(defun something-else (a &optional b)
  (interactive
   (let* ((a-local (read-number "First num: "))
          (b-local (when (< a-local 2)
             (read-number "Second num: "))))
     (list a-local b-local)))
  (message "a is %s, b is %s" a b))

In the above example a-local and b-local are variables with names of your choice wich are local to the enclosing let*-form. The star in let* means that the evaluated expression (read-number "First num: ") for a-local is assigned to a-local before the expression (when (< a-local 2) (read-number "Second num: ")) for b-local is evaluated.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice one. I ended up using this form* to avoid leaking global symbols.
4
(defun xtest (a &optional b)
  (interactive
   (let (a b)
     (setq a (read-number "First: "))
     (if (< a 2)
         (setq b (read-number "Second: ")))
     (list a b)))

  (message "a is %s b is %s" a b))

2 Comments

Great. Added elegance to the somewhat clumsy "anonymous" interactive declaration. I've been pondering this for years, thanks!
i find using setq in this example more readable. The other answer is already using let*.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.