1
$\begingroup$

I am trying to set the value of a global variable X from inside a function.

I want the value of this variable to change when the function is called. The function will also return the string "pass" when called.

Here is the code:

function[] := (
   X = 10;
   Return["pass"];
   );

However, when I set a new value for X in the function, then call the function

function[]

and then call X, I get the OLD value of X, implying that X was never changed.

How would I go about doing this?

$\endgroup$
  • 1
    $\begingroup$ I can't reproduce the problem. $\endgroup$ – andre314 Feb 29 '20 at 23:45
  • $\begingroup$ I suggest you restart the kernel and try again. $\endgroup$ – andre314 Feb 29 '20 at 23:46
  • 2
    $\begingroup$ You must reevaluate the definition of the function. That said, changing a global from a local context (the function) in this way is just not good practice. $\endgroup$ – ciao Feb 29 '20 at 23:46
  • 1
    $\begingroup$ To analyse the problem you can evaluate ??function and see if there is something abnormal. You can paste screenshot in the question above too. $\endgroup$ – andre314 Feb 29 '20 at 23:50
1
$\begingroup$

Evaluate this in a new session with a clean notebook.

x = 42;
function[] := (
  x = 10;
  "pass"
  )

Note that you do not need to use Return. A Wolfram Language function always returns the last expression it evaluates.

Evaluate

Dynamic[x]

You should get the output 42, the current value of x. Now evaluate

function[]

You should get the output pass and the output below Dynamic[x] should change to 10. Dynamic is very useful for tracking the changes to global variables when debugging.

$\endgroup$

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.