Scoping constructs Block, Module, ModuleBlock violate principle of
- To: mathgroup at smc.vnet.net
- Subject: [mg111100] Scoping constructs Block, Module, ModuleBlock violate principle of
- From: Michael <michael2718 at gmail.com>
- Date: Tue, 20 Jul 2010 03:44:03 -0400 (EDT)
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[] and
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 also
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
- Follow-Ups:
- Re: Scoping constructs Block, Module, ModuleBlock violate principle of
- From: Patrick Scheibe <pscheibe@trm.uni-leipzig.de>
- Re: Scoping constructs Block, Module, ModuleBlock violate principle of