Emacs Lisp:如何使用交互式(用于条件参数)?

时间:2014-08-22 12:41:51

标签: elisp

我想根据第一个问题的答案向用户提出第二个问题。

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

所以我需要一种方法来测试条目值:

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

但是

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

问题:如何以真正互动的方式使用interactive

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分:3)

interactive中的表单解释为一种子程序,它将参数值列表作为返回值传递。 你可以在let之类的表格中使用局部变量。

(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))

在上面的示例中,a-localb-local是您所选择的名称的变量,它们是封闭式let* - 表单的本地名称。 let*中的星标表示在评估(read-number "First num: ")的表达式a-local之前,a-local的已评估表达式(when (< a-local 2) (read-number "Second num: "))已分配给b-local。< / p>