Prev: Scoping constructs Block, Module, ModuleBlock violate principle of
Next: Brillouin function for a Ferromagnet
From: István Zachar on 20 Jul 2010 07:55 I think the answer for your DynamicModule-related question is: DynamicModule *does not* wrap its local variables in Dynamic. It is never stated in the Documentation. Morover, it is somewhat explicitely stated, that you *should use* Dynamic wrappers when needed: "DynamicModule[{x,y,...},expr] represents an object which maintains the same local instance of the symbols x, y, ... in the course of all evaluations of Dynamic objects in expr. ... " The following produces the behaviour you're looking for: DynamicModule[{n = 7}, Row[{Dynamic@n, Button["X", --n; Print[n]]}]] Cheers Istv=E1n On Jul 20, 9:44 am, Michael <michael2...(a)gmail.com> wrote: > This statement yields unexpected behavior: > > DynamicModule[{n = 7}, > Row[{n, Button["X", --n; Print[n]]}] > ] > > Why doesn't the "n" that appears as the first element in Row[] change > when I click on the button? The Print[] statement clearly shows it is > being decremented. I can look at "n" outside of the DynamicModule[] an= d > see that it is not defined, so Button[] can't be working with a > different "n" than Row is trying to display, can it? > > n2=7; > Dynamic[ > Row[{n2, Button["X", --n2; Print[n2]]}] > ] > > This behaves as expected, but I need localization and this doesn't > provide it. Ok, I will use a Block[]. But wait... > > Block[{n3 = 7}, > Dynamic[ > Row[{n3, Button["X", --n3; Print[n3]]}] > ] > ] > > Mathematica highlights n3 in Red, and n3 appears to lose its value > inside the Dynamic. I have looked, but I can't find anything in the > documentation for Block[] or Dynamic[] suggesting this sort of behavior. > > Ok, how about a Module[] instead of a Block[]? > > Module[{n3 = 7}, > Dynamic[ > Row[{n3, Button["X", --n3; Print[n3]]}] > ] > ] > > This works fine. So why doesn't DynamicModule[] work??? There is al= so > another problem with this approach. I might want to define a more > complex interface than just a button: > > f[x_] := Button[x, --n3; Print[n3]] > Module[{n3 = 7}, > Dynamic[ > Row[{n3, f["X"]}] > ] > ] > > This is why I wanted to use Block[] or even DynamicModule[], because > then f[] would see n3 in the context of the Block. But since Module[] > creates internally some name like n3$1, f[] can't see it. > > I'm using Version 7. > > What's going on here? Any suggestions on how I can accomplish what > seemed like any easy task but wound up eating up my entire evening with > nothing to show for it? > > Thanks, > > Michael |