Efrain Romano
Efrain Romano

Reputation: 31

How do I evaluate "&optional argument" in emacs lisp?

I dont understand how to evaluate "&optional argument" in emacs lisp.

My code is:

(defun test-values (a &optional b)

  "Function with an optional argument (default value: 56) that issues a 
message indicating whether the argument, expected to be a
number, is greater than, equal to, or less than the value of 
fill-column."

(interactive "p")

(if (or (> a b)(equal a b))
  (setq value a)
(setq value fill-column)
(message "The value of payina is %d" fill-column))

**(if (equal b nil)
  (setq value 56)))**

In the first part, everything is perfect if I evaluate (test-values 5 4) or (test-values 5 5).

But, when I evaluate (test-values 5 ()) or (test-values 5 nil), I have the following error:

**Debugger entered--Lisp error: (wrong-type-argument number-or-marker-p nil)
  >(5 nil)
  (or (> a b) (equal a b))
  (if (or (> a b) (equal a b)) (setq value a) (setq value fill-column) 
(message "The value of payina is %d" fill-column))
  test-values(5 nil)
  eval((test-values 5 nil) nil)
  eval-last-sexp-1(nil)
  eval-last-sexp(nil)
  call-interactively(eval-last-sexp nil nil)
  command-execute(eval-last-sexp)**

Can anyone help me, please? Thanks.

Upvotes: 2

Views: 4132

Answers (2)

Efrain Romano
Efrain Romano

Reputation: 31

Thanks to Drew and Stephen Gildea.

I took your suggest and the ligth develope, and now i take the code.

I invert the flow and nest (anide) the second if, this is the last code.

Thank you very much.

The code is for EMACS LISP.

Greetings from Mexico.

(defun test-values (a &optional b)

  "Function with an optional argument that tests wheter its argument, a  
number, is greater than or equal to, or else, less than the value of 
fill-column, and tells you which, in a message. However, if you do not 
pass an argument to the function, use 56 as a default value."

(interactive "p")

(if (equal b nil)
    (setq value 56)
  (if (or (> a b)(equal a b))
      (setq value a)
    (setq value fill-column)
    (message "The value of test is %d" fill-column))))


(test-values 6 3)

(test-values 3 3)

(test-values 3 6)

(test-values 6 nil)

(test-values 6)

Now I can evaluate this function with nil.

Thanks a lot.

Upvotes: 1

Stephen Gildea
Stephen Gildea

Reputation: 385

Optional arguments not supplied are bound to nil. In the body of your function you can test for nil explicitly before doing arithmetic. In your flow you might set b to 56 like this:

(or b (setq b 56))

Upvotes: 5

Related Questions