0
$\begingroup$

An example of the problem I am encountering:

choices = {"A", "B", "C", "D", "E"};
buttons = {};
callMe[n_] := Module[{}, MessageDialog[choices[n]]];
test[] := Module[{},
   buttons = {};
   Scan[AppendTo[buttons, Button[#, callMe[Length@buttons + 1]]] &, choices];
   Return@buttons;
];
test[]

The call to test displays a list of buttons. When I click on one of these, I want the 'n_' argument to 'callMe' to contain the index into 'choices' from which that button got its caption. But this is not what happens. n_ is always equal to 6 (the last value of 'Length@buttons+1'), no matter which button is clicked. I've tried various combinations of ReleaseHold, Evaluate, etc. This is most likely quite simple, but I can't get anything to work. Can someone point me in the right direction?

$\endgroup$
5
  • 1
    $\begingroup$ Button is HoldRest so you need to inject Length@buttons there. With[{l=Length...}, Button...] $\endgroup$ – Kuba Jun 9 '18 at 6:59
  • $\begingroup$ Of course that works, and I think you've answered a nearly identical question for me in the past. Thanks Kuba, for your help and your patience. $\endgroup$ – M. Robinson Jun 9 '18 at 7:19
  • 2
    $\begingroup$ @M.Robinson Your question goes basically under label "simple mistake". However, Attributes of functions lead more than often to unexpected behavior. Would you go ahead and post an answer to your question? $\endgroup$ – halirutan Jun 10 '18 at 1:41
  • $\begingroup$ @M.Robinson I could not find the answer you've mentioned even though I remember it too :p Linked topics should cover that problem, let me know if you disagree. $\endgroup$ – Kuba Jun 11 '18 at 6:51
  • $\begingroup$ @halirutan -- for this example (sorry, don't know how to format messages): choices = {"A", "B", "C", "D", "E"}; buttons = {}; callMe[n_] := Module[{}, MessageDialog[choices[[n]]]]; test[] := Module[{}, buttons = {}; Scan[With[{t = Length@buttons + 1}, AppendTo[buttons, Button[#, callMe[t]]]] &, choices]; Return@buttons; ]; test[] $\endgroup$ – M. Robinson Jun 16 '18 at 2:52

Browse other questions tagged or ask your own question.