Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate[] seems to not work inside Button[]

Any idea how to get this to work?

y = {}; Table[Button[x, AppendTo[y, Evaluate[x]]], {x, 5}]

Result: Click [1] , click [2], get {6,6}

I'm trivializing the actual task, but the goal is to set what a button does inside a Map or a Table or ParallelTable.

Please Help!


EDIT
Figured it out... Evaluate works at first level only. Here, it's too deep. So I used ReplaceRule:

Remove[sub]; y = {}; Table[Button[x, AppendTo[y, sub]] /. sub -> x, {x, 5}]
like image 525
Gregory Klopper Avatar asked Sep 23 '11 03:09

Gregory Klopper


1 Answers

This is a job for With. With is used to insert an evaluated expression into another expression at any depth -- even into parts of the expression that are not evaluated right away like the second argument to Button:

y = {}; Table[With[{x = i}, Button[x, AppendTo[y, x]]], {i, 5}]

In simple cases like this, some people (myself included) prefer to use the same symbol (x in this case) for both the With and Table variables, thus:

y = {}; Table[With[{x = x}, Button[x, AppendTo[y, x]]], {x, 5}]
like image 184
WReach Avatar answered Oct 04 '22 00:10

WReach