3

Say there is a defmacro defined like this:

(defmacro do-something (foo &optional bar)
  (...))

And then there is another one that calls it:

(defmacro something-else (wat baz &optional bar)
  (let ((foo (concat wat baz)))
    (do-something ...)))

What is the best practice for calling do-something from within something-else with the let variable foo, and bar only if it exists as an argument passed into something-else?

I know you could conditionally check the presence of bar like so:

    (if bar
        (do-something foo bar)
      (do-something foo))

Ideally I'm looking for some pattern where I can prepare a list of argument variables and call do-something once, with something like (apply) for macros, where a list variable can be turned into a variable series of consecutive arguments. Or maybe I'm just thinking about this in the wrong manner?

2
  • I'm not really sure what you're asking, but wouldn't simply (when bar (do-something foo bar)) work?
    – nanny
    Nov 9, 2015 at 16:46
  • Sorry, I guess I didn't explain my question well enough. Added some more background about what I'm asking.
    – waymondo
    Nov 9, 2015 at 17:39

1 Answer 1

1

Based on the code you've written, you can simply replace this:

(if bar
    (do-something foo bar)
  (do-something foo))

With this:

(do-something foo bar)

Because optional arguments default to nil. From the Emacs Lisp manual:

If actual arguments for the optional and rest variables are omitted, then they always default to nil. There is no way for the function to distinguish between an explicit argument of nil and an omitted argument.

http://www.gnu.org/software/emacs/manual/html_node/elisp/Argument-List.html

7
  • Its my understanding that passing bar as nil into (do-something) is technically different than omitting the optional variable. Is this never the case?
    – waymondo
    Nov 9, 2015 at 18:20
  • @waymondo From the Emacs Lisp manual: "There is no way for the function to distinguish between an explicit argument of nil and an omitted argument." gnu.org/software/emacs/manual/html_node/elisp/… You may be confusing this behavior with Common Lisp.
    – nanny
    Nov 9, 2015 at 19:16
  • @nanny Nope, trying to tackle this issue. Using the if condition is a hack that actually works. Nov 9, 2015 at 19:20
  • @kaushalmodi That's an interesting problem, I'll look into it as well. I'm inclined to say that the Emacs manual is not lying, and this isn't a bug with Emacs, but with one of the packages involved.
    – nanny
    Nov 9, 2015 at 19:53
  • 1
    @kaushalmodi I think I found the problem. I think it lies with the bind-key macro. I will open an issue/PR.
    – nanny
    Nov 9, 2015 at 21:12

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.