Talespin_Kit
Talespin_Kit

Reputation: 21877

How to increment local variables in elisp

I am trying to write a loop in elisp which prints the values sequencially.

I have tried the following code to print the sequence from 1.. which does not work. Please point the error in the code.

(let ((inc_variable 0))
  (message "%S" inc_variable)
  (while t (let ((inc_variable (+ inc_variable 1)))
    (message "%S" inc_variable))))

Upvotes: 7

Views: 4766

Answers (2)

Adobe
Adobe

Reputation: 13477

Another way to increment variable is to use cl-incf from cl-lib:

(require 'cl-lib)
(let ((x 0))
  (cl-incf x)
  (message "%d" x)
)

The loop might look like this:

(require 'cl-lib)
(let ((x 0))
  (while (< x 10) (cl-incf x)
         (insert (format "%d\n" x))
  )
)

Upvotes: 10

Gareth Rees
Gareth Rees

Reputation: 65854

There are two bindings for inc_variable in this code. The outer binding has the value 0 and never changes. Then, each time round the loop, you create a new binding for inc_variable that gets set to one plus the value of the outer binding (which is always 0). So the inner binding gets the value 1 each time.

Remember that let always creates a new binding: if you want to update the value of an existing binding, use setq:

(let ((inc-variable 0))
  (while t 
    (message "%S" inc-variable)
    (setq inc-variable (+ inc-variable 1))))

Upvotes: 11

Related Questions