Page 1 of 1

buffer name as variable

Posted: Sun Nov 22, 2009 11:57 am
by rubing
I am working through the FSF text: An Introduction to Programming in Emacs Lisp. I am having some trouble with the following buffer exercise:
Use if and get-buffer to write a function that prints a message telling you whether a buffer exists.
Here is the program I wrote:

(defun buf-exists (bufpos)
"tests to see if the buffer named bufpos exists"
(interactive)
(save-excursion
(if (get-buffer bufpos))
(message "%s def exists" bufpos)
(message "sorry there is no buffer named %s" bufpos)))


It fails for some reason to bind the named buffer passed as an argument to the variable bufpos. Any Advice?? THanks!

Re: buffer name as variable

Posted: Tue Nov 24, 2009 11:51 pm
by ramarren
There are two problems with this function. One, the interactive form doesn't match the number of arguments. You need argument designator for every non-optional function argument, in this case something like "M". Second, which would be very visible if the code was indented, the two MESSAGE forms are outside the scope of the IF form. Remember, Lisp is supposed to written with parentheses, but read by indentation.

This is obviously wrong:

Code: Select all

(defun buf-exists (bufpos)
  "tests to see if the buffer named bufpos exists"
  (interactive)
  (save-excursion
    (if (get-buffer bufpos))
    (message "%s def exists" bufpos)
    (message "sorry there is no buffer named %s" bufpos)))
and should be:

Code: Select all

(defun buf-exists (bufpos)
  "tests to see if the buffer named bufpos exists"
  (interactive "M")
  (save-excursion
    (if (get-buffer bufpos)
        (message "%s def exists" bufpos)
      (message "sorry there is no buffer named %s" bufpos))))

Re: buffer name as variable

Posted: Thu Nov 26, 2009 11:17 am
by rubing
Yes, those are some needed changes, but the function still does not work. If for example I type:

(buf-exists *scratch*)

and try to evaluate, I get the error (void-variable *scratch*)

Re: buffer name as variable

Posted: Thu Nov 26, 2009 11:33 am
by ramarren
rubing wrote:(buf-exists *scratch*)
Standard Lisp evaluation rules mean that when the first element in the form is a standard function, first the remaining elements are evaluated to obtain the arguments to be passed to a function. Symbols, which is what '*scratch*' is are treated as variables, and evaluating them means obtaining the value of the variable, which in this case is, as the error message tells you, non-existent.

In any case, buffers are not named with symbols, but with strings.

Code: Select all

(buf-exists "*scratch*")
works.

Re: buffer name as variable

Posted: Thu Nov 26, 2009 11:36 am
by Paul Donnelly
rubing wrote:Yes, those are some needed changes, but the function still does not work. If for example I type:

(buf-exists *scratch*)

and try to evaluate, I get the error (void-variable *scratch*)
That's because *scratch* doesn't exist. Put it in quotes.