0

Have been playing with the following function

(defun ignition (featr actm)
  "TODO."

  (when (eq 'sweep featr) (setq featr 'icomplt))
  (message "%S" featr))

Calling the following sequence of commands

(setq featr 'sweep)
(ignition featr actm)
(message "%S" featr)

gives the following result

icomplt
sweep

Meaning that inside the function, the argument featr is only changed locally, whereas getting back from the function keeps the value of featr to sweep before calling the function.

Is this the way things work in elisp? Does changing the value of an argument inside a function tolerable?

Would programmers looking at the code usually complain if someone changes argument value inside the function?

With the transition to lexical binding, would this code still be valid?

3
  • "tolerable"? what does that mean?
    – NickD
    Nov 3, 2022 at 14:20
  • Would programmers looking at the code usually complain if someone changes argument value inside the function?
    – Dilna
    Nov 3, 2022 at 14:34
  • Why don't you edit your question to say that?
    – NickD
    Nov 3, 2022 at 14:49

1 Answer 1

0

To understand how this works, you should read about Scoping Rules for Variable Bindings.

The paramaters of the function definition become local variables within the function body.

If you would like to set the global value of 'featr' then use:

(defun ignition (featr actm)
  "TODO."

  (when (eq 'sweep featr) (setq featr 'icomplt))
  (print featr))

(setq featr 'sweep actm 'test)
(setq featr (ignition featr actm))
(message "%S" featr)
5
  • I can see that you pass the return of the function to reset the global one. I understand it. It is usual to change the value locally as I have done in elisp packages?
    – Dilna
    Nov 3, 2022 at 9:31
  • I am not sure if I understand your question, but when you create a local variable (as a parameter) with the same name as some global variable, then you can only change the value of that local variable within the scope, I think. Nov 3, 2022 at 9:38
  • Now that emacs uses lexical binding for most files, are there any implications to my code? Have read the dynamic versus lexical binding and am not quite sure about how things will affect my coding.
    – Dilna
    Nov 3, 2022 at 9:41
  • As far as I can find in Scoping Rules for Variable Bindings, Emacs uses dynamic binding by default. However, it is recommended to write your packages using lexcial binding. If it has implications for your code depends on how you have written your code, but I guess you have not enabled lexical binding anyway in your packages. Nov 3, 2022 at 9:51
  • My file all have the declaration lexical-binding: t. Implications referred with regards the example I have shown.
    – Dilna
    Nov 3, 2022 at 10:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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