4

The following elisp code inserts hello world! 10 times:

-*- lexical-binding: t -*-
(dotimes (i 10) (insert "hello world!\n"))

If I byte-compile that code, I get the following message:

hellos.el:2:1:Warning: Unused lexical variable `i'

This is strange ... i is used to count from 0 to 9, even if it is not used in the repeated code. How am I supposed to loop 10 times ?!

Even stranger, the warning message disappears if I set

-*- lexical-binding: nil -*-

Go figure ...

Is this a bug (admittedly minor) in the emacs compiler? Is there a way to loop 10 times without using a counting variable?

10

You don't use i and that's what the byte-compiler tells you. To let the byte-compiler know that you're aware of the fact that the variable is unused, give it a name that starts with an underscore. E.g.

(dotimes (_ 10) ...)

or

(dotimes (_i 10) ...)
  • Thanks !! BTW, why is the byte-compiler not complaining when lexical-binding is not set? – phs Feb 19 '16 at 17:33
  • 7
    Because with dynamic scoping the byte compiler can't be sure that the variable is really not used (e.g. the insert function in your example could theoretically make use of it). – Stefan Feb 19 '16 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.