Search code examples
variableslispelispeval

Is it mandatory to evaluate a LISP variable before using it?


I'm new to ELISP and LISP in general. Here's some example code:

(setq number 2)

(* 8 number)

In lisp interaction mode, I can use the key combination control+j at the end of a line and it should evaluate it inline. If I try to do this at the second line of code (* 2 number), I get an error message:

Debugger entered--Lisp error: (void-variable number)
  (* 8 number)

My assumption is that number isn't registered as having a value. If I perform control+j on the first line of code (setq number 2), then I can use control+j on the second just fine.

My question is, is my assumption that because the first value wasn't evaluated, the second one cannot be correct? And also, is there a better way to register these values, in interactive mode, than to do it line by line? I assume that when this application is ran normally, outside of being inside Emacs, this isn't an issue, just an issue when evaluating code on-the-fly inside Emacs.


Solution

  • What happens is that Elisp (and other Lisps like Common Lisp) generally evaluate forms. In this case, you have two forms, corresponding to your two lines.

    (setq number 2)
    
    (* 8 number)
    

    Combination C-j specifically evaluates (and prints) a form. Another option that works, and which I tend to use is C-x C-e which evaluates the form preceding the cursor. That is, if you want to evaluate your (setq number 2), you would place the cursor after the ).

    To evaluate the entire buffer, you can use M-x eval-buffer. That will evaluate the entire thing you have written in the current buffer. For instance, your number variable would become "known" after that.

    Also, this question thread may be helpful to read.