开发者

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开发者_JS百科)
  (while t (let ((inc_variable (+ inc_variable 1)))
    (message "%S" inc_variable))))


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))))


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))
  )
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜