# Button action evaluation [duplicate]

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?

• Button is HoldRest so you need to inject Length@buttons there. With[{l=Length...}, Button...] – Kuba Jun 9 '18 at 6:59
• 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. – M. Robinson Jun 9 '18 at 7:19
• @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? – halirutan Jun 10 '18 at 1:41
• @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. – Kuba Jun 11 '18 at 6:51
• @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[] – M. Robinson Jun 16 '18 at 2:52