Use let for local variable

To define a variable in Elisp, mostly local variable, it's better to use let or let* instead of setq, they might look the same but different.

With setq, you'll get the reference to free variable warnings, which is not acceptable if you going to submit the package to MELPA or somewhere similar.

To use let, use the syntax:

(let ((variable-name value)
      (variable-name-2 value-2))

Remember to have the pair of () wrapping around the declaration section of let statement, it must be present even if you're creating a single variable.

About the execution order, all of the value expressions will be evaluated in the order they appear, before any binding, hence, the following snippet may not work as we expected:

(let ((y 1)
      (z y))
  (print y z))

The variable z might not be binded with the old value of y, not the value 1 as it appear in the first statement.

So, in short, the evaluation of value expressions is the order they appeared, but the binding order is unspecified.

To make the binding happen in the exact order they appeared (or, the binding will happen right after the value expression is evaluated), use let*, for example:

(let* ((y 1)
       (z y))
  (print y z))

Now, the code will evaluate the value of the statement (y 1), then bind the y with 1, so, z will now guaranteed to have value of 1.

For more detailed information, see M-x elisp-index-search (type: let).

Date: 2019-01-06 Sun 00:00

Author: Huy Tran

Created: 2019-04-22 Mon 14:41