A bit of a revision after 12 years of development in Emacs has gone.
To clarify about some differences between set, setq and other mentioned. Those functions are not equal and each function serves a purpose. They are often interchangeable, but not always!
The most important to remember:
- set sets the value cell of special symbols (global values), even in lexical scope.
- setq depending on the context can set the value cell of a global variable too, but if used in the lexical context it will set the value of the variable visible in the current lexical environment. If a variable is declared as a buffer-local variable, than it will always set buffer-local value of the variable.
- setf Same as setq, but with additional powers
setf function not mentioned in answers above, is a "generalized" setq in newer Emacs versions. It should probably be your first and the only choice when setting non-Customize variables. In compiled code it will be just as efficient as setq but it has additional powers to "figure out" a place rather than just use the name of a variable.
To set Customize variables use either customize-set-variable or the newer, setopt function made especially for setting Customize variables and which functions a lot like setq. Setopt is added in Emacs 29, on a popular request. Read what the manual says about setting variables too, and check the setopt docs in your Emacs: C-h f setopt RET.
I would just like to add that in new Emacs, it is a bad advice to use setq as your first get-go for variables defined in Customize interface.
The reason is that a variable might have a specialized code defined in custom-set property that might not run to properly initialize the variable if you use setq to set it.
You can also see this answer by Drew and definitely check the elisp manual for Customize.
Unfortunately, I am new here and couldn't comment under the relevant advice, so I had to make this as an answer. I am also writing this ~12 years after the original answer, please don't see it as a critique to the previous answers. Some of those things didn't even exist back than! I mean it more as an addendum or errata due to changes in Emacs.
defvar
but onlysetq
then you can only override the value after you load the package. However you should never usesetq
withoutdefvar
in your package if the user can change the value. If you use a package written properly, there is no difference between usingsetq
orcustom
. – Kiersten