# How to create a table with buttons?

I'd like to make a simple dice roller to be used in board games. A simple way to simulate a roll is:

d[n_] := RandomChoice[Range[n]]


Now, calling d will roll a 6-sided die, and d a 20 sided-die. To avoid typing the command each time, it can be made into a button:

Button["d20", Echo@d]


I wanted to build a Button table to simulate the classic range of d4, d6, d8, d10, d12 and d20. My initial try of:

Table[Button["d" <> ToString[k], Echo@d[k]], {k, {4, 6, 8, 10, 12, 20}}]


fails to run. I got no better result with:

ButtonBar[Table["d" <> ToString[k] :> d[k], {k, {4, 6, 8, 10, 12, 20}}]]


How can I generate this list ?

Try this:

buttons = Button["d" <> ToString[#], Echo@d[#]] & /@ {4, 6, 8, 10, 12, 20};

Column[buttons]


or

ButtonBar["d" <> ToString[#] :> Echo@d[#] & /@ {4, 6, 8, 10, 12, 20}]


Of course, from this example it's easy to customise the style.

For example, I would change d[n)] as follows:

d[n_] := "d" <> ToString[n] <> ": " <> ToString[RandomChoice[Range[n]]]


so that the output tells you which dice you rolled.

• Is there any reason why you prefer to use string expressions (~~) as opposed to concatenation (<>) ? – Whelp Jan 29 '20 at 17:11
• No, actually I think StringJoin (<>) would be more appropriate here :) I'll edit the answer with that! – Fraccalo Jan 29 '20 at 17:13

You can use With[{k = k}, ...] to inject the iterator values in the first argument in Table:

Table[With[{k = k}, Button["d" <> ToString[k], Echo@d[k]]], {k, {4, 6, 8, 10, 12, 20}}]


Alternatively, define a function outside Table and use it as the first argument in Table:

btn[x_] := Button["d" <> ToString[x], Echo@d[x]]
Table[btn[k], {k, {4, 6, 8, 10, 12, 20}}]


Similarly, for ButtonBar:

ButtonBar[Table[With[{k = k}, "d" <> ToString[k] :> Echo@d[k]], {k, {4, 6, 8, 10, 12, 20}}]]


or

rule[x_] := "d" <> ToString[x] :> Echo@d[x];
ButtonBar[Table[rule[k], {k, {4, 6, 8, 10, 12, 20}}]]

• Interesting. I was wondering how it could be done that way, thanks. – Whelp Jan 29 '20 at 17:59