I want to create a plot using Dynamic
. Ideally, I'd have some persistent, locally scoped state variables living in a Module
; as these variables are updated the plot should change.
I've tried defining a function within the Module
scope: calling this function updates the state variables. From the Module
, I return both the plot object and the function. Both can be passed around wherever I need them, but calling the function from anywhere needs to always update the plot.
ClearAll[callback, plot];
{callback, plot} = Module[{plot, callfunc, currPath, currT0, currT1},
currPath = Function[{t}, 0.0];
currT0 = 0.0;
currT1 = 1.0;
plot = Dynamic[Plot[currPath[t], {t, currT0, currT1}]];
callfunc = Function[{pp, t0, a, t1, b}, (
currPath = pp;
currT0 = t0;
currT1 = t1;
)];
{callfunc, plot}];
Here's what I've got so far. This works when calling the function directly in the frontend but not in other circumstances, and also there are red-highlighted warning texts everywhere. Perhaps I should be using DynamicModule
, but in that case I can't return values from it in the same straightforward way (it doesn't just return the 2-element list, it includes lots of other stuff too).
What's the right way for me to do this?
Edit:
I think I have this working now.
Do[callback[4*#&, 0.0,1.0,1.0,1.0],{i,5}]
worked as expected. However,
Do[callback[i*#&, 0.0,1.0,1.0,1.0],{i,5}]
failed. This was a scoping issue. The fix is:
Do[callback[Module[{ii=i},ii*#&], 0.0,1.0,1.0,1.0],{i,5}]
On the other hand, the frontend still gives me glaring red warnings in this code, which suggests I'm doing something wrong. Can someone explain this?
Module
, butModule
does not give you persistently scoped symbols: it implements lexical scoping, meaning that the variable are only localized to the bit of code you put inside of theModule
. When you usecallback
outside of theModule
the localization is gone. The fact that is works at all should be more surprising than that is sometimes fails. What you probably want here, are variables that live in a different context. Read the documentation forBegin
and see if that does what you need. $\endgroup$Module
the localization is gone." The localization is given by the unique symbol name, and that is still around outside theModule
. Just examine the definitions? callback
and? plot
, and evaluate theModule
variables found in it. $\endgroup$